I was writing a program to unpack Uint8
and Uint32
integers from a stream, and encountered this issue where I couldn’t pass a non-multiple-of-4
value as start
argument of Uint32List.sublistView()
function. I understand that end - start
should be a multiple of 4, but why should the value of start
be multiple of 4?
Example:
Assume that I have a byte stream which represents an array of Uint32s. The first byte of the stream is a Uint8 value representing the count of Uint32 values. Below is a simplified version of the code I am trying to accomplish.
import 'dart:typed_data';
void main() {
// First byte (2) represents the number of Uint32 values. The 2 Uint32 values are 7 and 5
// represented in Endian.little. Please note this is just a simplified representation,
// I do have other data elements in my original byte stream.
var bytes = Uint8List.fromList([2, 7, 0, 0, 0, 5, 0, 0, 0]);
// I would just like pull the Uint32 values list without performing any copy.
// as in the below line.
var uint32List = Uint32List.sublistView(bytes, 1, 1 + bytes[0]*4);
// However, the above line throws
// RangeError: Offset (1) must be a multiple of BYTES_PER_ELEMENT (4) error.
// Instead I have to copy the bytes to a different buffer
// or use some kind of iteration over ByteData. like:
var elements = Uint8List.fromList(Uint8List.sublistView(bytes, 1)); // copy bytes
print(Uint32List.sublistView(elements)); // prints [7, 5]
}
Dart documentation: https://api.dart.dev/stable/3.4.4/dart-typed_data/Uint32List/Uint32List.sublistView.html