How do I read a 16-bit int from a Uint8List in Dart?

时间:2015-07-28 22:15:36

标签: dart

I have a binary data stored in Uint8List and I'd like to read a 16-bit int from that list. Are there any convenience methods to help with this?

(paraphrasing from a conversation I had with a colleague)

2 个答案:

答案 0 :(得分:6)

You can use the ByteData class:

var buffer = new Uint8List(8).buffer;
var bytes = new ByteData.view(buffer);
bytes.getUint16(offset);

(paraphrased from an answer provided by a colleague)

答案 1 :(得分:1)

正如Seth所说,你想要一个Uint8List二进制数据的ByteData视图。

使用ByteBuffer.asByteData()稍微好一些。 它更简洁,更适合测试。 如果你有一个模拟Uint8List和一个模拟ByteBuffer,new ByteData.view(buffer)将失败,但模拟ByteBuffer的asByteData()方法可以返回一个模拟ByteData。

var bytes = myUint8List.buffer.asByteData();
bytes.getUint16(offset);

凭借完美的远见,我们只有asByteData()而不是冗余的公共ByteData.view构造函数。