readFromBufferAsFloat function

double readFromBufferAsFloat(
  1. Pointer<Uint8> buffer,
  2. int offset,
  3. int byteCnt
)

Read a specified piece of the buffer and convert it to a floating point number.

If offset is aligned, tat is if (offset mod byteCnt) = 0, the function chooses more efficient implementation. On unaligned data, byte-by-byte copying takes place. The only valid values for byteCnt are 4 (Float) and 8 (Double). Any other will cause a MemException.

Implementation

double readFromBufferAsFloat(Pointer<Uint8> buffer, int offset, int byteCnt) {
  if (offset % byteCnt == 0) {
    // offset is aligned
    switch (byteCnt) {
      case 4:
        return Pointer<Float>.fromAddress(buffer.address + offset)
            .asTypedList(1)[0];
      case 8:
        return Pointer<Double>.fromAddress(buffer.address + offset)
            .asTypedList(1)[0];
      default:
        throw MemException("Invalid byte count value: $byteCnt");
    }
  } else {
    // offset is not aligned - copying byte by byte
    final bytes = Uint8List(byteCnt);
    for (var i = 0; i < byteCnt; i++) {
      bytes[i] = buffer[offset + i];
    }
    return fromBytesAsFloat(bytes);
  }
}