How to read 16-bit int from Uint8List in Dart?

I have binary data stored in a Uint8List, and I would like to read the 16-bit int from this list. Are there any convenient methods for doing this?

(paraphrasing the conversation I had with a colleague)

+6
source share
2 answers

You can use the ByteData class:

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

(paraphrased from a response provided by a colleague)

+6
source

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 Uint8List layout and mock ByteBuffer, new ByteData.view(buffer) will fail, but the mock ByteBuffer asByteData() method can be made to return mock ByteData.

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

With perfect foresight, we will only have asByteData (), not the redundant public ByteData.view constructor.

+1
source