首页 > 解决方案 > 从 Uint8List Dart 解析 int 和 float 值

问题描述

我正在尝试使用此库解析从蓝牙设备收到的 int 和 double 值:https ://github.com/Polidea/FlutterBleLib

我收到以下 Uint8List 数据:31,212,243,57,0,224,7,1,6,5,9,21,0,1,0,0,0,91,228

我在这里找到了一些帮助:How do I read a 16-bit int from a Uint8List in Dart?

在 Android 上我做了一些类似的工作,但是那里的库有所谓的值解释器,我只传递数据并接收回浮点/整数。

来自 Android 的示例代码:

int offset = 0;
final double spOPercentage = ValueInterpreter.getFloatValue(value, FORMAT_SFLOAT, offset);

value字节数组在哪里

另一个来自android代码的例子,这个代码如果来自库:

public static Float getFloatValue(@NonNull byte[] value, int formatType, @IntRange(from = 0L) int offset) {
    if (offset + getTypeLen(formatType) > value.length) {            
        return null;
    } else {
        switch(formatType) {
        case 50:
            return bytesToFloat(value[offset], value[offset + 1]);
        case 52:
            return bytesToFloat(value[offset], value[offset + 1], value[offset + 2], value[offset + 3]);
        default:               
            return null;
        }
    }
}

private static float bytesToFloat(byte b0, byte b1) {
    int mantissa = unsignedToSigned(unsignedByteToInt(b0) + ((unsignedByteToInt(b1) & 15) << 8), 12);
    int exponent = unsignedToSigned(unsignedByteToInt(b1) >> 4, 4);
    return (float)((double)mantissa * Math.pow(10.0D, (double)exponent));
}
private static float bytesToFloat(byte b0, byte b1, byte b2, byte b3) {
    int mantissa = unsignedToSigned(unsignedByteToInt(b0) + (unsignedByteToInt(b1) << 8) + 
        (unsignedByteToInt(b2) << 16), 24);
    return (float)((double)mantissa * Math.pow(10.0D, (double)b3));
}
private static int unsignedByteToInt(byte b) {
    return b & 255;
}

在颤振/飞镖中,我想编写自己的价值解释器。起始示例代码是:

int offset = 1; 
ByteData bytes = list.buffer.asByteData(); 
bytes.getUint16(offset);

我不明白如何在 dart 中操作数据以从数据列表的不同位置获取 int 值。我需要一些解释如何做到这一点,如果有人可以对此进行一些教学,那就太好了。

标签: dartbluetooth

解决方案


具有以下内容:

values [31, 212, 243, 57, 0, 224, 7, 1, 6, 5, 9, 21, 0, 1, 0, 0, 0, 91, 228];
index    0    1    2   3  4    5  6  7  8  9 10  11 12 13 14 15 16  17   18

当你做:

values.list.buffer.asByteData().getUint16(0);

您将 [31, 212] 解释为两个字节长度的单个无符号整数。

如果您想从字节 9 和 10 [5, 9] 中获取 Uint16,您可以调用:

values.list.buffer.asByteData().getUint16(9);

关于您的评论(解析来自 Uint8List Dart 的 int 和 float 值):

我有这个 Uint8List 值是:31、212、243、57、0、224、7、1、6、5、9、21、0、1、0、0、0、91、228 我使用代码下面 ByteData 字节 = list.buffer.asByteData(); 整数偏移 = 1;双值 = bytes.getFloat32(offset); 我期望的值应该在 50 到 150 之间 有关我正在做的事情的更多信息可以在这里找到:bluetooth.com/wp-content/uploads/Sitecore-Media-Library/Gatt/... name="SpO2PR-Spot-检查 - SpO2"

这个属性是 SFLOAT 类型的,根据https://www.bluetooth.com/specifications/assigned-numbers/format-types/看起来像这样:

0x16 SFLOAT IEEE-11073 16 位 SFLOAT

由于 Dart 似乎没有一种简单的方法来获取该格式,因此您可能必须自己使用原始字节创建解析器。

这些可能会有所帮助:

https://stackoverflow.com/a/51391743/6413439

https://stackoverflow.com/a/16474957/6413439


推荐阅读