【问题标题】:How to convert 2 bytes to Int16 in dart?如何在飞镖中将 2 个字节转换为 Int16?
【发布时间】:2020-05-17 14:55:57
【问题描述】:

在java的bitconverter类中有一个方法叫toInt16

但在飞镖中,我无法将 short 作为 Int16

public static short toInt16( byte[] bytes, int index )
                            throws Exception {
        if ( bytes.length != 8 )
            throw new Exception( "The length of the byte array must be at least 8 bytes long." );
        return (short) ( ( 0xff & bytes[index] ) << 8 | ( 0xff & bytes[index + 1] ) << 0 );
 }

有人可以帮我转换成飞镖语言吗?

这是我使用 emerssso 建议的 ByteData 类所遵循的更新 dart 版本的答案,这对我有用

int toInt16(Uint8List byteArray, int index)
{
    ByteBuffer buffer = byteArray.buffer;
    ByteData data = new ByteData.view(buffer);
    int short = data.getInt16(index, Endian.little);
    return short;
}

我必须专门设置 Endian.little 因为最初 getInt16 方法设置为 BigEndian 但我的字节数据是以前的订购

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    我认为您正在寻找dart:typed_data 中可用的ByteData 类方法之一。通过ByteData.view() 将字节数组包装在ByteData 中,然后您可以任意访问指定类型的字节。然后你可以这样做,即byteData.getInt16(index);

    https://api.dart.dev/stable/2.7.1/dart-typed_data/ByteData-class.html

    【讨论】:

      猜你喜欢
      • 2022-11-24
      • 2021-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多