floatFromBytes16 static method

double floatFromBytes16(
  1. List<int> bytes
)

Decodes a 16-bit float from bytes (big-endian) into a double.

Implementation

static double floatFromBytes16(List<int> bytes) {
  if (bytes.length != 2) {
    throw BuError(
      DefaultErrorType.invalidArgument,
      "Invalid bytes for float16.",
    );
  }

  final byteData = ByteData.sublistView(Uint8List.fromList(bytes));
  final bits = byteData.getUint16(0, Endian.big);

  final sign = (bits >> 15) & 0x1;
  var exponent = (bits >> 10) & 0x1F;
  final fraction = bits & 0x3FF;

  if (exponent == 0x1F) {
    if (fraction == 0) {
      return sign == 0 ? double.infinity : double.negativeInfinity;
    }
    return double.nan;
  }
  if (exponent == 0 && fraction == 0) {
    return sign == 0 ? 0.0 : -0.0;
  }

  exponent -= 15;
  return (sign == 0 ? 1.0 : -1.0) *
      (1.0 + fraction / 1024.0) *
      math.pow(2.0, exponent);
}