Print a binary number in C
Explanation here.
1 2 #include <stdio.h> 3 4 /* Print n as a binary number */ 5 void printbitssimple(int n) { 6 unsigned int i; 7 i = 1<<(sizeof(n) * 8 - 1); 8 9 while (i > 0) { 10 if (n & i) 11 printf("1"); 12 else 13 printf("0"); 14 i >>= 1; 15 } 16 } 17 18 /* Print n as a binary number */ 19 void printbits(int n) { 20 unsigned int i, step; 21 22 if (0 == n) { /* For simplicity's sake, I treat 0 as a special case*/ 23 printf("0000"); 24 return; 25 } 26 27 i = 1<<(sizeof(n) * 8 - 1); 28 29 step = -1; /* Only print the relevant digits */ 30 step >>= 4; /* In groups of 4 */ 31 while (step >= n) { 32 i >>= 4; 33 step >>= 4; 34 } 35 36 /* At this point, i is the smallest power of two larger or equal to n */ 37 while (i > 0) { 38 if (n & i) 39 printf("1"); 40 else 41 printf("0"); 42 i >>= 1; 43 } 44 } 45 46 int main(int argc, char *argv[]) { 47 int i; 48 for (i = 0; i < 16; ++i) { 49 printf("%d = ", i); 50 printbitssimple(i); 51 printf("\n"); 52 } 53 54 return 0; 55 } 56