C convert to binary

Associate
Joined
18 Mar 2007
Posts
291
Hi guys,

I need to convert a decimal number into a binary one. Are there any built in functions to do this, or what would be the best way?

Cheers
 
Do you want to print a number out in binary?

I don't think there is anything in the C library to do that, but it's not too hard to do yourself. Basically you just have to check if the number is even or odd, if it's even concatenate "0" onto the end of the string, if it's odd concatenate a "1". Then left shift your integer by 1 (equivalent to dividing by 2). Repeat until your integer is equal to 0.
 
Do you want to print a number out in binary?

I don't think there is anything in the C library to do that, but it's not too hard to do yourself. Basically you just have to check if the number is even or odd, if it's even concatenate "0" onto the end of the string, if it's odd concatenate a "1". Then left shift your integer by 1 (equivalent to dividing by 2). Repeat until your integer is equal to 0.

You need to be a little careful with the order you do things in; this will print the binary in little-endian bit order (backwards) ;)
 
You need to be a little careful with the order you do things in; this will print the binary in little-endian bit order (backwards) ;)

Oh yeah, of course it will. Just reverse it afterwards, or insert each character in front of the last.
 
Back
Top Bottom