Question

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.

Was it helpful?

Solution

Your mask needs to be binary 00001111, which is equal to hex 0x0F.

byte mask = (byte)0x0F;

OTHER TIPS

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.

With java 7 you can create binary literals

byte binaryLit = (byte)0b00001111;

0xsomenumbers is a hex literal, and pre java7 there is no support for binaries.

You say you want to mask the first three bits but as Petar says, 0x001111 are not bits. If you want to mask the three bits you need to mask with 7

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top