Search code examples
javabit-manipulationbytebytecodebytebuffer

How do I get the 4bit from a 16 bit data?


I used getShort() method of byteBuffer to get me a short value, I converted it into a int and printed the binary value, which is a 16bit data, I need to access the int value of the starting 4bit from this 16bit data.

short bitRateShort = buf.getShort(32 + 2);
int bitRateInteger = Short.toUnsignedInt(bitRateShort);
System.out.println(bitRateInteger);//46144
System.out.println(Integer.toBinaryString(bitRateInteger));// 1011010001000000

I need to get the integer value for the starting 4bit which in my case is 1011, How can I mask this 16 bits to get 4bit nibble?


Solution

  • Try this:

    int bitRateInteger = 46144;
    System.out.println(Integer.toBinaryString(bitRateInteger&0xF000));
    System.out.println(Integer.toBinaryString((bitRateInteger&0xF000)>>12));
    

    Output:

    1011000000000000
    1011
    

    First, we mask the starting 4 bits with bitmask 0xF000 (binary 0b1111_0000_0000_0000). Then, we shift the resulting bits to the right by 12, to get rid of the "known" zeros at the end.

    Edit: As @CarlosHeuberger so kindly pointed out, you don't even need to do an & operation, because >> will truncate away all the right-side bits by default. So, do this instead:

    int bitRateInteger = 46144;
    System.out.println(Integer.toBinaryString(bitRateInteger>>12));
    

    Output:

    1011