binary conversion crash

I'm testing out Qt, and I've written a binary conversion widget. First my conversion algorithm was like this:
1
2
3
4
5
6
7
8
9
QString output = "";
long val = decimal_in->text().toLong();
long bit = 0;
while(val > 0) {
	bit = val%2;
	val = (val/2);
	output.append(QString::number(bit));
}
binary_out->setText(output);


This ran fine, but I made a mistake. The new algorithm is like this:
1
2
3
4
5
6
7
8
9
QString output = "";
long val = decimal_in->text().toLong();
long bit = 0;
while(val > 0) {
	bit = val%2;
	val = (val-bit/2); //ADDED -BIT
	output.append(QString::number(bit));
}
binary_out->setText(output);


This is the correct algorithm, but after I changed it, the program stops responding. GDB tells me nothing. Anyone have any ideas?
Ok, sorry, changed it to (val-bit)/2, wich runs again. But it's giving me wrong output! If I enter the value 2, it returns the binary value of 01!
First, even val/2 will work, because this is integer division. It automatically rounds down. You should prepend, not append, because you are extracting the least significant digit first.

Regards
Try this :

# include <iostream>
# include <conio.h>
using namespace std;
void main ()
{
int i=0,mas[100],number=0,rest=0,res;
cout<<" Enter decimal number \n>";
cin>>number;
do{
res=number/2;
rest=number%2;
mas[i]=rest;
number=res;
i++;
}
while(res>=2);
cout<<" Binary is : "<<res;
for(int c=0;c<i;c++){
cout<<mas[c];
}
cout<<"\n\n";
}
you can easily use itoa_ function for conversion,but it's not standart
Topic archived. No new replies allowed.