How to print a 5 bit/n bit number in C? -
let's have int x. want print first 5 bits of x. how can this? i've heard can like
printf("%d", x & 0x05);
to print first 5 bits of x outputs 0 in function.
if compiling gcc, visual studio 2015 (or later), or clang, can use 0b
(binary) prefix, can see bitmask want, instead of 0x
(hexadecimal) prefix, little less intuitive.
int x = 127; printf("%d\n", x & 0b11111000); // prints 120 printf("%d\n", x & 0b00011111); // prints 31
these examples mask out 3 least significant bits (1, 2 , 4), or 3 significant bits (64, 32 , 16), leaving other 5.
if compiling compiler not listed above, can import boost_binary macro.
if want view actual bits, might want see this question.
Comments
Post a Comment