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)
A fixed-length list of 8-bit unsigned integers. For long lists, this implementation can be considerably more space- and time-efficient than the default List implementation. Integers stored in the list are truncated to their low eight bits, interpreted as an unsigned 8-bit integer with values in the range 0 to 255.
ByteData can save space, by eliminating the need for object headers, and time, by eliminating the need for data copies. If data comes in as bytes, they can be converted to ByteData by sharing the same buffer. Uint8List bytes = ...; var blob = ByteData. sublistView(bytes); if (blob. getUint32(0, Endian.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With