0

I am new to Java. I have 8 bytes (or dlc bytes ) of data in Java, which looks like this :

int dlc = 8;
byte[] myData = new byte[dlc];

Then I would like to get the value (start bit is 50, length is 2 bits) from myData.

My idea is to convert myData to bits, then find the value start from bits 50 and has a length of 2 bits, then convert the bits values to integer, is this method good ? if it's available, then how to do it in java ? if it's not, any ideas to pick out some part of value from bytes array ?


Solution : The solution is provided by @Zoyd

NOTE : BitSet.valueOf(Bytebuffer) is added from Android API 19! so if you have earlier API level, you cannot use valueOf() method. You can look at BitSet to and from integer/long

Community
  • 1
  • 1
Heidi
  • 161
  • 5
  • 16

3 Answers3

1

try this

(myData[6] & 0x60) >> 5
Xing Fei
  • 287
  • 1
  • 6
1

Xing Fei's anwer is fine, but if you need a general method, you can make a BitSet from your byte array :

final BitSet bs = BitSet.valueOf(myData);

Then, you can write, for example :

boolean b = bs.get(50);

to obtain the value of bit 50.

Zoyd
  • 3,449
  • 1
  • 18
  • 27
0

In explanation of Xing Fei: myData[6] gives you bits 49 to 56, by AND-ing this with 0x60 (= 01100000) you set bits 49, 52, 53, 54, 55, and 56 to zero. If you shift this 5 bits to the right (>> - Operator) you have your result.

Jan
  • 2,060
  • 2
  • 29
  • 34