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

天大地大妈咪最大 提交于 2021-01-26 10:34:13

问题


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)


回答1:


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)




回答2:


As Seth said, you want a ByteData view of the Uint8List binary data.

It is slightly better to use ByteBuffer.asByteData(). It is a little more concise and works better for testing. If you have a mock Uint8List and a mock ByteBuffer, new ByteData.view(buffer) will fail, but the mock ByteBuffer's asByteData() method could be made to return a mock ByteData.

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

With perfect foresight we would only have asByteData() and not also a redundant public ByteData.view constructor.



来源:https://stackoverflow.com/questions/31688061/how-do-i-read-a-16-bit-int-from-a-uint8list-in-dart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!