Sajal Singh
Sajal Singh

Reputation: 385

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?

Upvotes: 2

Views: 1211

Answers (2)

Avi
Avi

Reputation: 2641

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

Upvotes: 3

SSP
SSP

Reputation: 2670

I agree with Avi answer.

Here is another approach :-

String first4char = Integer.toBinaryString(bitRateInteger).substring(0,4);
int intForFirst4Char = Integer.parseInt(first4char);

System.out.println(intForFirst4Char );

Upvotes: 0

Related Questions