Home > Enterprise >  Best way to grab 6 most significant bits from an unsigned int using operators in C?
Best way to grab 6 most significant bits from an unsigned int using operators in C?

Time:09-21

I have managed to get rid of the first couple of bits but how would I only keep only the 6 most significant bits in C? I have tried ((num << 6) & 1) with no luck

CodePudding user response:

To get the most significant six bits of an integer and not the rest, bitwise AND it with a mask with the high six bits set and the rest clear.

Because unsigned int is a pure binary type, its maximum value, UINT_MAX, has all its bits set. Then UINT_MAX >> 6 shifts those to the right, producing a result with the high six bits clear and the rest set. Performing a bitwise NOT, ~ (UINT_MAX >> 6), produces a result with the high six bits set and the rest clear.

Then num & ~ (UINT_MAX >> 6) produces the high six bits of num with the remaining bits clear.

UINT_MAX is declared in <limits.h>. Due to C’s wrapping arithmetic for unsigned types, you can also get the maximum value of an unsigned int by using -1u, so num & ~ (-1u >> 6) will also work.

CodePudding user response:

Universal method not depending on the width of the integer

#define  C6B(num) ((num) & ~((1ull << (sizeof(num) * CHAR_BIT - 6)) - 1))
  • Related