[英]Extracting Nibbles from Java Bytes
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
So I get 11 bytes (Hex) in over the serial port. 因此,我通过串行端口获得了11个字节(十六进制)。 I assigned all the bytes to a byte array so that I can use them later.
我将所有字节分配给一个字节数组,以便以后使用。
I have two qestions: 我有两个问题:
1] How can I combine the 4 & 5 bytes back together in Java (I am presuming in an INT) ? 1]如何在Java中将4和5个字节重新组合在一起(我在INT中假定)? 2] How can you extract 10 and 11 or the High and Low nibbles of the last byte ?
2]如何提取最后一个字节的10和11或高半字节和低半字节?
[FROM COMMENTS BELOW] Example Byte: High[0101][0110]Low lowNibble = yourbyte & 0x0f; [下面的注释]字节示例:高[0101] [0110]低lowNibble = yourbyte&0x0f; 01010110 & 0x0f (00001111) = 00000110
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) It depends on the endianness. 1)取决于字节序。 It will either be
(b[4] << 8) | b[5]
要么是
(b[4] << 8) | b[5]
(b[4] << 8) | b[5]
or (b[5] << 8) | b[4]
(b[4] << 8) | b[5]
或(b[5] << 8) | b[4]
(b[5] << 8) | b[4]
2) lowNibble = yourByte & 0x0f; highNibble = (yourByte >> 4) & 0x0f;
2)
lowNibble = yourByte & 0x0f; highNibble = (yourByte >> 4) & 0x0f;
lowNibble = yourByte & 0x0f; highNibble = (yourByte >> 4) & 0x0f;
You can also do: lowNibble = yourByte & 0x0f; highNibble = yourByte >>> 4;
您也可以这样做:
lowNibble = yourByte & 0x0f; highNibble = yourByte >>> 4;
lowNibble = yourByte & 0x0f; highNibble = yourByte >>> 4;
The unsigned shift ( >>>
) fills the upper bits with zero, regardless of the sign. 无符号移位(
>>>
)会将零填充高位,而与符号无关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.