Let's say I have some int x. I only want to print the first 5 bits of x. How can I do this? I've heard that I can do something like
printf("%d", x & 0x05);
to print the first five bits of x but this just outputs 0 in my function.
Let's say I have some int x. I only want to print the first 5 bits of x. How can I do this? I've heard that I can do something like
printf("%d", x & 0x05);
to print the first five bits of x but this just outputs 0 in my function.
If you are compiling with GCC, Visual Studio 2015 (or later), or Clang, then you can use the 0b
(binary) prefix, so you can see the bitmask that you want, instead of the 0x
(hexadecimal) prefix, which is a little less intuitive.
int x = 127;
printf("%d\n", x & 0b11111000); // Prints 120
printf("%d\n", x & 0b00011111); // Prints 31
These examples will mask out the 3 least significant bits (1, 2 and 4), or the 3 most significant bits (64, 32 and 16), leaving only the other 5.
If you are compiling with a compiler not listed above, then you can always import the BOOST_BINARY macro.
If you want to view the actual bits, then you might want to see this question.