java中的bitconverter类中有一个方法,该方法具有一个称为toInt16的方法
但是在dart中,我无法像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 );
}
有人可以帮助我转换为 Dart 语言吗?
这是我使用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 ,但是我的字节数据是以前的顺序
最佳答案
我认为您正在寻找dart:typed_data
中提供的ByteData类上的方法之一。通过ByteData
将字节数组包装在ByteData.view()
中,然后您可以任意访问指定类型的字节。然后,您可以执行byteData.getInt16(index);
。
https://api.dart.dev/stable/2.7.1/dart-typed_data/ByteData-class.html
关于flutter - 如何在Dart中将2个字节转换为Int16?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60012343/