首页 > 解决方案 > 在 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函数中我需要弄清楚如何解析数据。

标签: javaarraysbytebit

解决方案


由于数量未与 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

推荐阅读