Converting Decimal to binary in C++

Associate
Joined
6 Mar 2009
Posts
495
Hey guys, im trying to create a program that converts a decimal number that the a user inputs and converts it into binary.

Im not sure how i would even start.

Any suggestions?? Thanks
 
There is a function "itoa" that you could use.

It converts from an Integer to Ascii in the base you specify.
For binary the base would be 2.

I am pretty sure that itoa isnt part of the ANSI C or C++ standard though so may not work on your compiler and will make your code un portable.

I have seen it used in production code.
 
oh yes, I see you want a routine to output a sting. Just recursively divide the number by 2 and test for a remainder. If no remainder then lowest digit is 0. Etc
 
I'm assuming this homework so you're not allowed to do it in the sensible fashion, yes?

You'll want to loop through looking for whether or not binary "digits" are set. I'd do this by using the binary '&' operator (not the '&&' operator!), and progressively shifting what I'm comparing it to. Do you understand what the & and >> or << operators do?
 
Back
Top Bottom