convertBinaryToDecimal static method

Decimal? convertBinaryToDecimal(
  1. BsonBinary binary
)

Implementation

static Decimal? convertBinaryToDecimal(BsonBinary binary) {
  Int64 high, low;
  binary.rewind();
  low = binary.readFixInt64();
  high = binary.readFixInt64();

  /// The Decimal class does not support a NaN field
  /// Return a null value
  if ((high & naNMask) == naNMask) {
    return null;
  }

  var isNegative = (high & signMask) == signMask;

  /// The decimal class does not manage infinite value
  /// return a very high values
  if ((high & infinityMask) == infinityMask) {
    if (isNegative) {
      return -infinityValue;
    }
    return infinityValue;
  }

  var isFiniteCase2 = (high & finite2Mask) == finite2Mask;

  Int32 exponent;
  Decimal significand, highSignificand;

  significand = Decimal.parse(low.toRadixString(10));
  // Unfortunately we have only an Int64 and not an UInt64
  if (low.isNegative) {
    significand += maxUInt64;
  }
  if (isFiniteCase2) {
    exponent = ((high & exponent2Mask) >> 47).toInt32();
    highSignificand = Decimal.parse(
        ((high & significand2Mask) | significand2impliedMask)
            .toRadixString(10));
  } else {
    exponent = ((high & exponent1Mask) >> 49).toInt32();
    highSignificand =
        Decimal.parse((high & significand1Mask).toRadixString(10));
  }
  if (exponent > maxExponent) {
    return Decimal.zero;
  }
  exponent = (exponent - 6176) as Int32;

  significand += highSignificand * maxUInt64;
  if (significand > maxSignificand) {
    significand = Decimal.zero;
  }
  if (isNegative) {
    significand = -significand;
  }

  return significand * _d10.pow(exponent.toInt());
}