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)
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)
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.