Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

bit

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?

like image 355
jsguy Avatar asked Nov 21 '25 00:11

jsguy


1 Answers

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

like image 185
Mooing Duck Avatar answered Nov 22 '25 15:11

Mooing Duck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!