从 Java 字节中提取半字节 [英] Extracting Nibbles from Java Bytes

查看:44
本文介绍了从 Java 字节中提取半字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 个字节(十六进制).我将所有字节分配给一个字节数组,以便稍后使用.

So I get 11 bytes (Hex) in over the serial port. I assigned all the bytes to a byte array so that I can use them later.

我有两个问题:

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

1] How can I combine the 4 & 5 bytes back together in Java (I am presuming in an INT) ? 2] How can you extract 10 and 11 or the High and Low nibbles of the last byte ?

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

[FROM COMMENTS BELOW] Example Byte: High[0101][0110]Low 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) 这取决于字节序.它要么是 (b[4] << 8) |b[5](b[5] <<8) |b[4]​​

1) It depends on the endianness. It will either be (b[4] << 8) | b[5] or (b[5] << 8) | b[4]

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

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

无符号移位 (>>>) 用零填充高位,而不管符号如何.

The unsigned shift (>>>) fills the upper bits with zero, regardless of the sign.

这篇关于从 Java 字节中提取半字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆