jsguy
jsguy

Reputation: 2179

How can you get the j first most significant bits of an integer in C++?

I know that to get the first j least significant bits of an integer you can do the following:

  int res = (myInteger & ((1<<j)-1))

Can you do something similar for the most significant bits?

Upvotes: 3

Views: 295

Answers (2)

Mooing Duck
Mooing Duck

Reputation: 66961

Simply right shift: (Warning, fails when you want 0 bits, but yours fails for all bits)

unsigned dropbits = CHAR_BIT*sizeof(int)-j;
//if you want the high bits moved to low bit position, use this:
ullong res = (ullong)myInteger >> dropbits; 
//if you want the high bits in the origonal position, use this:
ullong res = (ullong)myInteger >> dropbits << dropbits;

Important! The cast must be the unsigned version of your type.

It's also good to note that your code for the lowest j bits fails when you ask it for all (32?) bits. As such, it can be easier to doubleshift:

unsigned dropbits = CHAR_BIT*sizeof(int)-j;
ullong res = (ullong)myInteger << dropbits >> dropbits;

See it working here: http://coliru.stacked-crooked.com/a/64eb843b3b255278 and here: http://coliru.stacked-crooked.com/a/29bc40188d852dd3

Upvotes: 2

Wintermute
Wintermute

Reputation: 44063

To get the j highest bits of an integer (or rather an unsigned integer, because bitwise operations in signed integers are a recipe for pain):

unsigned res = myUnsignedInteger & ~(~0u >> j);

~0u consists of only set bits. Shifting that j bits to the right gives us j zero-bits on the left side followed by one-bits, and inverting that gives us j one-bits on the left followed by zeroes, which is the mask we need to isolate the j highest bits of another integer.

Note: This is under the assumption that you want the isolated bits to remain in the same place, which is to say

(0xdeadbeef & ~(~0u >> 12)) == 0xdea00000

Upvotes: 2

Related Questions