0

我有一个以 ieee754 半精度浮点格式提供温度数据的设备,即[78, 100] = +25.5C.
现在,Dart/Flutter 不支持开箱即用的 HP-Float 转换。在谷歌搜索之后,我发现了几种解决方案,我能够将它们组合成一个似乎工作正常的解决方案。多年来没有这样做,我要求专业人士检查一下。此外,我相信这将为像我这样需要此功能的人节省一些时间。这已经在 -10C 到 +35C 的温度下进行了测试,并且似乎可以正确转换两种方式。这里_ieee754HpBytesToDouble将 HPF 字节转换为 64 位双精度,_ieee754HpBytesFromDouble并将 64 位双精度字节转换为半精度字节。

  ///
  /// Double to Uint8List
  ///
  Uint8List _ieee754HpBytesFromDouble(double fval) {
    int result = _doubleToBits(fval);
    Uint8List beef = _int32bytes(result);
    return Uint8List.fromList(beef.reversed.skip(2).toList());
  }

  ///
  /// Double to hp-float bits
  ///
  int _doubleToBits(double fval) {
    ByteData bdata = ByteData(8);
    bdata.setFloat32(0, fval);
    int fbits = bdata.getInt32(0);

    int sign = fbits >> 16 & 0x8000;
    int val = (fbits & 0x7fffffff) + 0x1000;

    if (val >= 0x47800000) {
      if ((fbits & 0x7fffffff) >= 0x47800000) {
        if (val < 0x7f800000) return sign | 0x7c00;
        return sign | 0x7c00 | (fbits & 0x007fffff) >> 13;
      }
      return sign | 0x7bff;
    }
    if (val >= 0x38800000) return sign | val - 0x38000000 >> 13;
    if (val < 0x33000000) return sign;
    val = (fbits & 0x7fffffff) >> 23;
    return sign |
        ((fbits & 0x7fffff | 0x800000) + (0x800000 >> val - 102) >> 126 - val);
  }

  ///
  ///
  ///
  Uint8List _int32bytes(int value) =>
      Uint8List(4)..buffer.asInt32List()[0] = value;

  ///
  ///
  ///
  double _bitsToDouble(int bits) {
    Uint8List list = _int32bytes(bits);
    ByteBuffer buffer = new Int8List.fromList(list.reversed.toList()).buffer;
    ByteData byteData = new ByteData.view(buffer);
    double result = byteData.getFloat32(0);
    return result;
  }

  ///
  ///
  ///
  double _ieee754HpBytesToDouble(List<int> i) {
    int hbits = i[0] * 256 + i[1];
    int mant = hbits & 0x03ff;
    int exp = hbits & 0x7c00;
    if (exp == 0x7c00)
      exp = 0x3fc00;
    else if (exp != 0) {
      exp += 0x1c000;
      if (mant == 0 && exp > 0x1c400) {
        return _bitsToDouble((hbits & 0x8000) << 16 | exp << 13 | 0x3ff);
      }
    } else if (mant != 0) {
      exp = 0x1c400;
      do {
        mant <<= 1;
        exp -= 0x400;
      } while ((mant & 0x400) == 0);
      mant &= 0x3ff;
    }
    return _bitsToDouble((hbits & 0x8000) << 16 | (exp | mant) << 13);
  }
4

0 回答 0