For example 0x19 is 00011001 in binary. I tried using printf %08x, but that gives me 00000019 as the output. How do I get it to print 00011001 instead?
Asked
Active
Viewed 58 times
-3
-
3Write your own function for that. – haccks Apr 01 '15 at 16:52
-
1use [itoa,utoa](http://manpages.ubuntu.com/manpages/utopic/en/man3/itoa.3avr.html)(non-standard) E.g. `char bits[32+1]; printf("%s\n", itoa(0x19, bits, 2));` – BLUEPIXY Apr 01 '15 at 17:14
-
http://stackoverflow.com/questions/111928/is-there-a-printf-converter-to-print-in-binary-format – BLUEPIXY Apr 01 '15 at 17:38
2 Answers
0
If itoa(non-standard function) can be used environment, can be written as follows.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
int main( void ){
char bits[CHAR_BIT*sizeof(unsigned)+1];
itoa((int)0x19, bits, 2);
int len = strlen(bits);
if(len < 8)//%08
printf("%0*d%s\n", 8-len, 0, bits);
else
printf("%s\n", bits);
return 0;
}

BLUEPIXY
- 39,699
- 7
- 33
- 70