hexToBn function

BigInt hexToBn(
  1. dynamic value, {
  2. Endian endian = Endian.big,
  3. bool isNegative = false,
})

Implementation

BigInt hexToBn(dynamic value,
    {Endian endian = Endian.big, bool isNegative = false}) {
  try {
    if (value == null) return BigInt.from(0);
    if (isNegative == false) {
      if (isHex(value)) {
        var sValue = value is num
            ? int.parse(value.toString(), radix: 10).toRadixString(16)
            : value;
        if (endian == Endian.big) {
          return BigInt.parse(
              hexStripPrefix(sValue) == '' ? '0' : hexStripPrefix(sValue),
              radix: 16);
        } else {
          return decodeBigInt(hexToBytes(
              hexStripPrefix(sValue) == '' ? '0' : hexStripPrefix(sValue)));
        }
      }
      var _sValue = value is num
          ? int.parse(value.toString(), radix: 10).toRadixString(16)
          : value;
      if (endian == Endian.big) {
        return BigInt.parse(_sValue, radix: 16);
      } else {
        return decodeBigInt(hexToBytes(
            hexStripPrefix(_sValue) == '' ? '0' : hexStripPrefix(_sValue)));
      }
    } else {
      var hex = value is num
          ? int.parse(value.toString(), radix: 10).toRadixString(16)
          : hexStripPrefix(value);
      if (hex.length % 2 > 0) {
        hex = '0' + hex;
      }
      hex = decodeBigInt(
              hexToBytes(hexStripPrefix(hex) == '' ? '0' : hexStripPrefix(hex)),
              endian: endian)
          .toRadixString(16);
      var bn = BigInt.parse(hex, radix: 16);

      if ((0x80 &
              int.parse(hex.substring(0, 2 > hex.length ? hex.length : 2),
                  radix: 16)) >
          0) {
        var some = BigInt.parse(
                bn.toRadixString(2).split('').map((i) {
                  return '0' == i ? 1 : 0;
                }).join(''),
                radix: 2) +
            BigInt.one;
        // print(some);
        // add the sign character to output string (bytes are unaffected)
        bn = -some;
      }
      return bn;
    }

    // return value is String ? BigInt.parse(value, radix: 16) : BigInt.from(value as num);
  } catch (e) {
    throw "Error: can not parse $value to BigInt";
  }
}