readFromBufferAsSigned function
Read a specified piece of the buffer and convert it to an integer number (signed).
If offset is aligned, tat is if (offset mod byteCnt) = 0,
the function is more efficient.
On unaligned data, byte-by-byte copying takes place.
The only valid values for byteCnt 1, 2, 4 and 8 (any other will
cause a MemException).
Implementation
int readFromBufferAsSigned(Pointer<Uint8> buffer, int offset, int byteCnt) {
if (offset % byteCnt == 0) {
// the offset is aligned
switch (byteCnt) {
case 1:
return Pointer<Int8>.fromAddress(
buffer.address + offset,
).asTypedList(1)[0];
case 2:
return Pointer<Int16>.fromAddress(
buffer.address + offset,
).asTypedList(1)[0];
case 4:
return Pointer<Int32>.fromAddress(
buffer.address + offset,
).asTypedList(1)[0];
case 8:
return Pointer<Int64>.fromAddress(
buffer.address + offset,
).asTypedList(1)[0];
default:
throw MemException(
"Invalid byte count for reading int from buffer: $byteCnt",
);
}
} else {
// the offset not aligned - copying byte by byte
final bytes = Uint8List(byteCnt);
for (var i = 0; i < byteCnt; i++) {
bytes[i] = buffer[offset + i];
}
return fromBytesAsSigned(bytes);
}
}