-1

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.

1 Answers1

1

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.

Addison
  • 7,322
  • 2
  • 39
  • 55
  • 0b is a non-standard extension supported by recent versions of gcc and clang, but not generally by other compilers – Chris Dodd Sep 11 '17 at 01:48
  • Huh. Touche @ChrisDodd. I always assumed this was part of the C standard, but you are indeed correct. I'll update to reflect that. – Addison Sep 11 '17 at 01:55