how can i convert a integer with radix 10 to a binary string with C without having the itoa function?
Asked
Active
Viewed 476 times
0
-
An integer (`int`, etc.) _is_ in binary. Do you want to convert a string? – Chris Lutz Mar 09 '11 at 21:55
-
1Please give an example of what you're looking for, as your question isn't clear. – Oliver Charlesworth Mar 09 '11 at 21:56
-
2possible duplicate of [Is there a printf converter to print in binary format?](http://stackoverflow.com/questions/111928/is-there-a-printf-converter-to-print-in-binary-format) – Adam Rosenfield Mar 09 '11 at 21:56
-
1Example input and expected output would make everything about this question clear. – Edwin Buck Mar 09 '11 at 21:58
1 Answers
0
You can print a '0' if the number is even or '1' if it is even, then divide by 2 and recurse. Only the other way around ... or something like that.
Example with 13
13 is odd so print 1 and divide by 2 giving 6 6 is even so print 0 and divide by 2 giving 3 3 is odd so print 1 and divide by 2 giving 1 1 is odd so print 1 and divide by 2 giving 0 0 reached so stop and read the printing backwards from this ^^^ column
13 is 1101 in binary

pmg
- 106,608
- 13
- 126
- 198
-
1Depending on architecture and compiler implementation, right-shift by one could be faster. (It certainly won't be slower.) – Cajunluke Mar 09 '11 at 22:08
-