Home > Back-end >  Do I have to set most significant bits to zero if I shift right?
Do I have to set most significant bits to zero if I shift right?

Time:06-26

Let's say I have a 64-bit number and some bits that are set that hold a value, let's say three bits. I have a mask to get that value. To get the value of those three bits I bitwise 'AND' the number with the mask. This sets all other bits to zero. I then need to shift right towards the least significant bits so the least significant bit of the three-bit number is in the position of the least significant bit of the 64 bit number. After I shift right, do I need to mask again to ensure only all the bits to the left of those three bits are zero?

CodePudding user response:

You can do shift first then the mask and accomplish what you want:

int value = 0xdeadbeef;
value >>= 15;
value &= 0x7;

CodePudding user response:

The way shift right works depends on the type of the argument:

int value = -1;
value >>= 10;

Assuming two's-complement, which you now can, this will use an arithmetic shift and preserves the sign bit. So after the shift the value will still be -1 and have all bits set. If you mask before the shift then after the shift you get more bits then you bargained for.

unsigned int value = 0xFFFFFFFF;
value >>= 10;

This will use a logical shift and add zeroes to the left. So if you mask before the shift then you still get the right bits after the shift.

But why mask before the shift? If you mask after the shift then you always get the right bits regardless of the type.

  • Related