Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain low and high order nybbles from byte within Java ByteBuffer

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!!

like image 887
Tony Avatar asked Jan 17 '23 08:01

Tony


1 Answers

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.
like image 153
Peter Lawrey Avatar answered Feb 15 '23 10:02

Peter Lawrey