Example 1
This example prints out ints in binary.
// ex1.cThis processes an int from right to left. It uses a "binary and" to get the rightmost bit, putting '1' for non zero and '0' in a buffer. This continues for as many digits as were specified in the second parameter to PrintBinary().
//
#include <stdio.h>
void PrintBinary(int x,int d)
{
char buffer[33];
int index;
index=0;
while (d >0) {
if (x & 1)
buffer[index++]='1';
else
buffer[index++]='0';
x >>= 1;
d--;
}
while (index >0 )
printf("%c",buffer[--index]) ;
printf("B\n") ;
return;
}
int main(int argc, char* argv[])
{
PrintBinary(10,6) ;
PrintBinary(8,4) ;
PrintBinary(32765,16) ;
return 0;
}
x >>= 1;This uses the right shift operator >> to rotate x by one bit to the right. This is exactly the same as dividing by 2 and many compilers use shift operations to optimize integer division. You could have used
x /= 2;instead but I think >>= is more true to the meaning, and the compiler will probably generate right shift anyway.
The buffer is filled out in reverse. so PrintBinary(10,6) for example puts 010100 in the buffer then prints it out in reverse in the while loop. This makes it very easy to add leading zeros.
On the next page More about this example

