floatFromBytes16 static method

double floatFromBytes16(
  1. List<int> bytes
)

Decode a 16-bit floating-point value from a byte array and return it as a double.

Implementation

static double floatFromBytes16(List<int> bytes) {
  if (bytes.length != 2) {
    throw ArgumentException(
        'Input byte array must be exactly 2 bytes long for Float16');
  }

  ByteData byteData = ByteData.sublistView(Uint8List.fromList(bytes));
  int int16Bits = byteData.getInt16(0, Endian.big);

  int sign = (int16Bits >> 15) & 0x1;
  int exponent = (int16Bits >> 10) & 0x1F;
  int fraction = int16Bits & 0x3FF;

  double value;

  if (exponent == 0x1F) {
    if (fraction == 0) {
      value = sign == 0 ? double.infinity : double.negativeInfinity;
    } else {
      value = double.nan;
    }
  } else if (exponent == 0 && fraction == 0) {
    value = sign == 0 ? 0.0 : -0.0;
  } else {
    exponent -= 15;
    value = sign == 0 ? 1.0 : -1.0;
    value *= (1.0 + fraction / 1024.0) * math.pow(2.0, exponent);
  }

  return value;
}