### Learning loops: decimal to binary

I can't figure out why my code isn't working. I am trying to convert the users input from base 10 to binary. I went through it a few times and I just cant figure out why it isn't running properly. Any help would be much appreciated!

 ``1234567891011121314151617181920212223242526272829`` `````` /* This program reads from the user a positive integer (in decimal representation), and prints its binary (base 2).*/ #include using namespace std; int main() { int decimal, power, result, remain; cout << "Enter decimal number:" << endl; cin >> decimal; power = log(decimal)/ log(2); while (decimal > 0) { result = 2 ^ power; remain = decimal - result; if (remain >= 1) { cout << "1"; decimal = decimal - result; } else { cout << "0"; } power = power - 1; } cout << endl; return 0; }``````
@capnrap,
I have to admit that I don't think this is a good way of doing the problem. A more common way would be to loop through looking at the end digit (decimal%2) and add character '0' or '1' at the start of a results string, followed by decimal /= 2 . Finally, print out the whole string.

However ... with your existing technique:
(1) ` result = 2 ^ power;` doesn't do what you think it does (^ is a bitwise operator; you would need pow())
(2) Your test for looping is wrong - you should test on remaining power, not decimal, as the binary representation might end ...000 and you do need to write those zeroes.
(3) You should write a '1' if decimal/result is non-zero, not if remain >= 1 (which is usually true).
(4) log() and pow() are phenomenally expensive operations when you only need to be multiplying or dividing by 2 (which can, in fact, be accelerated by bitshifting).
(5) Consider using a separate function - you are tying down main() to just doing this single number conversion.

With the caveat that I REALLY DON'T THINK THIS IS A GOOD WAY OF DOING THE PROBLEM, minimal changes to your code are below. Note that it will only work for a number strictly greater than zero.
 ``123456789101112131415161718192021222324252627282930`` ``````/* ***** This is NOT A GOOD WAY OF DOING THE PROBLEM **** */ #include #include // you need this header for log() and pow() using namespace std; int main() { int decimal, power, result; cout << "Enter decimal number:" << endl; cin >> decimal; power = log(decimal)/ log(2); // this is clunky ... and may well fail due to floating-point round-off while (power >= 0) // test on remaining positions, NOT residual number - you may have to write ...000 { result = pow(2,power); // 2 ^ power does NOT do what you think it does if ( decimal / result !=0 ) { // correct your test for a non-zero digit cout << "1"; decimal = decimal - result; } else { cout << "0"; } power = power - 1; } cout << endl; return 0; }``````

Last edited on