如何在飞镖中将 2 个字节转换为 Int16?



java中的bitconverter类中有一种方法,它有一个名为toInt16的方法

但是在飞镖中,我无法像 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 类遵循的答案的更新飞镖版本,这对我有用

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,但我的字节数据是以前的顺序

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

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

最新更新