Skip to content

Instantly share code, notes, and snippets.

@programmer-ke
Last active March 8, 2017 08:11
Show Gist options
  • Save programmer-ke/f9c960d833effaf3b8f89eeec530e328 to your computer and use it in GitHub Desktop.
Save programmer-ke/f9c960d833effaf3b8f89eeec530e328 to your computer and use it in GitHub Desktop.
Print out a bits in an unsigned integer in C
void binary_print(unsigned int value) {
unsigned int mask = 0xff000000; // start with a mask for the highest byte
unsigned int shift = 256*256*256; // start with a shift for the highest byte
unsigned int byte, byte_iterator, bit_iterator;
for(byte_iterator=0; byte_iterator < 4; byte_iterator++) {
byte = (value & mask) / shift; // isolate each byte
printf(" ");
for(bit_iterator=0; bit_iterator < 8; bit_iterator++) { // print the byte's bits
if(byte & 0x80) // if the highest bit in the byte isn't 0
printf("1"); // print a 1
else
printf("0"); // otherwise print a 0
byte *= 2; // move all the bits to the left by 1
}
mask /= 256; // move the bits in mask right by 8
shift /= 256; // move the bits in shift right by 8
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment