doubleToFloat16 static method

int doubleToFloat16(
  1. num n
)

Implementation

static int doubleToFloat16(num n) {
  final f = n.toDouble();
  final xI = float32ToUint32(f);
  if (f == 0.0) {
    // Common special case - zero.
    // Preserve the zero's sign bit.
    return xI >> 16;
  }

  if (_toFloatFloat32Data == null) {
    _initialize();
  }

  // We extract the combined sign and exponent, e, from our
  // floating-point number, f. Then we convert e to the sign
  // and exponent of the half number via a table lookup.
  //
  // For the most common case, where a normalized half is produced,
  // the table lookup returns a non-zero value; in this case, all
  // we have to do is round f's significand to 10 bits and combine
  // the result with e.
  //
  // For all other cases (overflow, zeroes, denormalized numbers
  // resulting from underflow, infinities and NANs), the table
  // lookup returns zero, and we call a longer, non-inline function
  // to do the float-to-half conversion.
  var e = (xI >> 23) & 0x000001ff;

  e = _eLut[e];

  if (e != 0) {
    // Simple case - round the significand, m, to 10
    // bits and combine it with the sign and exponent.
    final m = xI & 0x007fffff;
    return e + ((m + 0x00000fff + ((m >> 13) & 1)) >> 13);
  }

  // Difficult case - call a function.
  return _convert(xI);
}