fromBytes static method

BigInt fromBytes(
  1. List<int> bytes, {
  2. int offset = 0,
  3. int? length,
  4. Endian byteOrder = Endian.big,
  5. bool sign = false,
})

Converts a list of bytes to a BigInt, considering byte order and sign.

offset specifies the starting index within bytes to read from. length specifies how many bytes to read (defaults to the rest of the list).

Implementation

static BigInt fromBytes(
  List<int> bytes, {
  int offset = 0,
  int? length,
  Endian byteOrder = Endian.big,
  bool sign = false,
}) {
  final int len = length ?? (bytes.length - offset);

  if (offset < 0 || len < 0 || offset + len > bytes.length) {
    throw CoreErrors.invalidOperationArguments(
      'fromBytes',
      name: 'offset',
      reason:
          'Invalid offset/length: offset=$offset, length=$len, bytes.length=${bytes.length}.',
    );
  }

  if (len == 0) return BigInt.zero;
  final BigInt byte256 = BigInt.from(256);

  BigInt result = BigInt.zero;
  int firstByte;

  if (byteOrder == Endian.little) {
    // Most significant byte is the last one in the range; walk backwards
    // from there without ever materializing a reversed copy.
    firstByte = bytes[offset + len - 1];
    for (var i = offset + len - 1; i >= offset; i--) {
      result = result * byte256 + BigInt.from(bytes[i]);
    }
  } else {
    firstByte = bytes[offset];
    for (var i = offset; i < offset + len; i++) {
      result = result * byte256 + BigInt.from(bytes[i]);
    }
  }

  if (sign && (firstByte & 0x80) != 0) {
    result -= BigInt.one << (len * 8);
  }

  return result;
}