java - 在 Java 中,如何从字节数组中读取 n 位?
问题描述
我正在尝试从我的血压袖带通过蓝牙接收的特定 ByteArray 中解析数据。根据本规范GATT 外观特性规范,数据是一个 16 位字节数组,具有两个值——一个类别(10 位)和子类别(6 位)。我不知道如何读取未存储在字节中的值。如何从字节数组中读取 16 位中的 10 位和 16 位中的 6 位?那么一旦我有 10 位,我是否必须用 6 个零填充它才能得到一个值?我假设这些不是标志当然是潜在的字符串值。
我一直在尝试了解有关按位运算的各种教程和指南,但它只是没有点击如何读取 10 位。
deviceConnection =
device.establishConnection(true)
.flatMapSingle {
for (g in gattCharacteristics) {
singles.add(it.readCharacteristic(g.uuid))
}
Single.zip(
singles
) { varargs ->
val values: MutableList<ByteArray> = mutableListOf()
for (v in varargs) {
values.add(v as ByteArray)
}
return@zip values
}
}
.observeOn(AndroidSchedulers.mainThread())
.take(1)
.subscribe(
{
characteristics.forEachIndexed { index, c ->
c.value = processByteArray(c.uuid, it[index])
}
serviceDetailsAdapter.notifyDataSetChanged()
},
{
onConnectionFailure(it)
}
)
然后在processByteArray
函数中我需要弄清楚如何解析数据。
解决方案
由于数量未与 8 位字节对齐,为了使事情更容易,首先将两个字节放在一起:
byte mostSignifant = byteArray[0];
byte leastSignifant =byteArray[1];
int bothBytes = (Byte.toUnsignedInt(mostSignifant) << 8) | Byte.toUnsignedInt(leastSignifant);
您的文档应该告诉您两个字节中的哪个是“最高有效字节”(MSB),哪个是最低字节(LSB) - 可能是索引 0 具有最低有效字节。
现在您可以提取所需的位,例如
int lower6Bits = bothBytes & 0b111111;
int higher10Bits = bothBytes >>> 6; // get rid of lower 6 bits
推荐阅读
- xcode - 在 XCTest UI 测试中单击 NSToolbarItem
- r - 结合两个数据框,相似的行,相似的列,除了一个列具有不同的值
- html - CSS Grid - 在中心上方对齐自我
- swift - SwiftUI 数组 - 忽略零值
- php - 为什么 Laravel 的 HTTP 内核中的路由使用完全限定的类名和 ::class?
- jquery - 滚动时导航未突出显示
- regex - 如何使用 RegExr 选择下面的部分
- ruby-on-rails - ruby on rails - git push heroku master stop on "remote: Building source:"
- java - Akka java.lang.AssertionError:expectMessage期间超时(3秒)等待
- sql - 使用链接表进行分组