I'm new to low level operations like this, I'm hoping someone can point out the obvious mistake I must be making here.
//Input value - 00111100
//I want to get the value of the bits at indexes 1-3 i.e 0111.
byte mask = (byte)0x00001111; // This gives 17 not the 15 I'd expect
byte shifted = (byte)(headerByte >> 3);
//shifted is 7 as expected
byte frameSizeValue = (byte)(shifted & mask); //Gives 1 not 7
It looks like the problem lies with the way the mask is defined, but I can't see how to fix it.
In computer science, a mask or bitmask is data that is used for bitwise operations, particularly in a bit field. Using a mask, multiple bits in a byte, nibble, word, etc. can be set either on or off, or inverted from on to off (or vice versa) in a single bitwise operation.
The logical bitwise XOR operator can be used with a mask to toggle a bit.
Bit masking is simply the process of storing data truly as bits, as opposed to storing it as chars/ints/floats. It is incredibly useful for storing certain types of data compactly and efficiently.
First of all 0x00001111
is in hex, which is a larger number than 255
- 16^3 + 16^2 + 16 + 1 = 4369
and byte
overflows. Look here how to represent binary numbers or just use shifted & 15
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With