Skip to content

Instantly share code, notes, and snippets.

@ajaysusarla
Created July 12, 2016 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajaysusarla/f0c1882402257780811e739db3f0fdb1 to your computer and use it in GitHub Desktop.
Save ajaysusarla/f0c1882402257780811e739db3f0fdb1 to your computer and use it in GitHub Desktop.
Print bits
#include <stdint.h>
#include <limits.h>
#define numbits(x) (sizeof(x) * 8)
#define max_signed_value_of_type(t) \
(INTMAX_MAX >> (numbits(intmax_t) - numbits(t)))
void print_bits(int num)
{
size_t bits = numbits(num);
int max = max_signed_value_of_type(num) + 1;
int i;
for (i = 0; i < bits; i++) {
if (i && (i % 8) == 0)
printf(" ");
printf("%u", !!(num & max));
num = num << 1;
}
printf("\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment