bigIntToBytes function

Uint8List bigIntToBytes(
  1. BigInt number, {
  2. int? outLen,
  3. Endian endian = Endian.big,
})

Encode a BigInt into bytes using big-endian encoding. This is I2OSP as defined in rfc3447.

Implementation

Uint8List bigIntToBytes(BigInt number,
    {int? outLen, Endian endian = Endian.big}) {
  int size = (number.bitLength + 7) >> 3;
  if (outLen == null) {
    outLen = size;
  } else if (outLen < size) {
    throw Exception('Number too large');
  }
  final result = Uint8List(outLen);
  int pos = endian == Endian.big ? outLen - 1 : 0;
  for (int i = 0; i < size; i++) {
    result[pos] = (number & _byteMask).toInt();
    if (endian == Endian.big) {
      pos -= 1;
    } else {
      pos += 1;
    }
    number = number >> 8;
  }
  return result;
}