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 const CborException(
        'Input byte array must be exactly 2 bytes long for Float16');
  }

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

  final int sign = (int16Bits >> 15) & 0x1;
  int exponent = (int16Bits >> 10) & 0x1F;
  final 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;
}