从Java字节中提取半字节

时间:2013-02-02 20:30:09

标签: java serial-port

Hex:[0A][52][08][01][01][01][00][CD][21][02][59]


0      [0A]
1      [52]         Packettype    = TEMP_HUM
2      [08]         subtype       = TH8 - 
3      [01]         Sequence nbr  = 1
4/5    [01][01]     ID            = 257
6/7    [00][CD]     Temperature   = 20.5 °C
8      [21]         Humidity      = 33
9      [02]         Status        = Dry
10     [5] *nibble           Signal level  = 5
11     [9] *nibble           Battery       = OK

所以我通过串口获得了11个字节(Hex)。 我将所有字节分配给一个字节数组,以便以后可以使用它们。

我有两个问题:

1]我如何结合4&用Java重新组合5个字节(我假设在INT中)? 2]如何提取最后一个字节的10和11或高和低半字节?

[来自下面的评论] 示例字节:高[0110]低                lowNibble = yourbyte&为0x0F;                01010110& 0x0f(00001111)= 00000110

           highNibble = yourByte >>>> 4
           01010110 >>> 4 = 00000101


          IF you use this Example Byte: High[1101][0110]Low
          highNibble = yourByte >>> 4
          11010110 >>> 4 = 00000101
          Because >>> removes the signed bit.

1 个答案:

答案 0 :(得分:5)

1)这取决于字节顺序。它可以是(b[4] << 8) | b[5](b[5] << 8) | b[4]

2)lowNibble = yourByte & 0x0f; highNibble = (yourByte >> 4) & 0x0f;

你也可以这样做:lowNibble = yourByte & 0x0f; highNibble = yourByte >>> 4;

无符号移位(>>>)用零填充高位,无论符号如何。