I want to know if one needs to mask a number before retrieving the value stored at a certain byte when doing bit shifting.
Take, for example, this code:
short b1 = 1;
short b2 = 2;
short b0 = (short)((b1 << 8) | b2); //store two values in one variable
Console.WriteLine(b0); //b1 and b2 combined
Console.WriteLine((b0 & (255 << 8)) >> 8); //gets the value of b1
As far as I am concerned, doing a right shift drops all bits that are less than the number of bits you've shifted. Therefore, right shifting b0
by 8 bits will drop the 8 bits of b2
, leaving just b1
.
Console.WriteLine(b0 >> 8); //this also gets b1!!
I want to find out, is there any need to mask b0
with 255 << 8
before shifting to get the value of b1
?
NB:
The only need I can think of for masking before retrieving a value is if there is something else stored at a higher byte, such as trying to get back the value of b2
, in which this code would be used:
Console.WriteLine(b0 & 255); //gets the value of b2
b1
andb2
byte
s, andb0
aushort
. Right shiftingushort
does not propagate the sign bit. - Michael Graczyk