4
votes

I need to extract two integer values from a byte stored within a ByteBuffer (little endian order)

ByteBuffer bb = ByteBuffer.wrap(inputBuffer);
bb.order(ByteOrder.LITTLE_ENDIAN);

The values I need to obtain from any byte within the ByteBuffer are:

length = integer value of low order nibble

frequency = integer value of high order nibble

At the moment I'm extracting the low order nybble with this code:

length = bb.getInt(index) & 0xf;

Which seems to work perfectly well. It is however the high order nybble that I seem to be having trouble interpreting correctly.

I get a bit confused with bit shifting or masking, which I think I need to perform, and any advice would be super helpful.

Thanks muchly!!

2
Please post the code you tried and describe exactly what's wrong with it. - Mat

2 Answers

8
votes

I need to extract two integer values from a byte

So you need to get a byte not an int, and the byte order doesn't matter.

int lowNibble = bb.get(index) & 0x0f; // the lowest 4 bits
int hiNibble = (bb.get(index) >> 4) & 0x0f; // the highest 4 bits.
1
votes

To get the high order nibble, all you need to do is bit shift; the low order bits will simply fall off.

int val = 0xAB;
int lo = val & 0xF;
int hi = val >> 4;
System.out.println("hi is " + Integer.toString(hi, 16));
System.out.println("lo is " + Integer.toString(lo, 16));