Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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)

like image 851
Seth Ladd Avatar asked Jul 28 '15 22:07

Seth Ladd


People also ask

What is Uint8List in Dart?

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.

What is byte in flutter?

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.


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 an answer provided by a colleague)

like image 192
Seth Ladd Avatar answered Sep 17 '22 14:09

Seth Ladd


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.

like image 23
Stephen Avatar answered Sep 16 '22 14:09

Stephen