Get low level nybbles from byte in Java ByteBuffer

I need to extract two integer values ​​from a byte stored in a ByteBuffer (small ordinal)

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

The values ​​I need to get from any byte in ByteBuffer are as follows:

length = lower order integer nibble

frequency = high order integer nibble

I am currently extracting the lower order using this code:

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

Which seems to work fine. However, as a rule, I usually have problems with interpretation.

I'm a bit confused about bit shifting or disguise, which I think I need to follow, and any advice would be very helpful.

Thanks a lot!

+4
source share
2 answers

I need to extract two integer values ​​from a byte

So you need to get the byte is not int, and the byte order does not matter.

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

To get the highest joke, all you have to do is shift the bits; the lower order bit will simply disappear.

 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)); 
+1
source

Source: https://habr.com/ru/post/1398855/


All Articles