dartcastingendianness

How to cast int to Uint8 in Dart?


Currently, I am trying to read a file byte by byte and add some specific values to a list of 8-bit bytes (which might be of type List<Uint8>). To read the file one byte at a time, I am using RandomAccessFile.readByte(), but it returns an int value which is not accepted by List<Uint8>.add() function.

Due to the function name and return type, it looks like RandomAccessFile.readByte() provides a single byte in 64 bits. So what is the proper way to get only the least significant byte of the 64 bit result and add it to _someUint8List considering different types of endianness?

Lastly, This page mentions Uint8 being a marker in Dart, but I am not sure what is meant by that. Thanks in advance.


Solution

  • That depends on what type Uint8 is.

    If it's the type from dart:ffi, then it's a native type, which means you cannot have a Dart value with that type. If you read a Pointer<Uint8>, it returns the value as an int, and you write an int to it as well, which gets truncated on write.

    Which means that you most likely don't have a List<Uint8>. You cannot, since there are no values of type Uint8 in the Dart heap. It's a native type that has to be converted to a Dart value, an int, when you access it from native memory.

    Use an Uint8List if the bytes are stored in the Dart heap, or a Uint8Array if they're stored in the native heap.