toBytes static method

List<int> toBytes(
  1. BigInt val, {
  2. int? length,
  3. Endian order = Endian.big,
})

Converts a BigInt to a list of bytes with the specified length and byte order.

Implementation

static List<int> toBytes(
  BigInt val, {
  int? length,
  Endian order = Endian.big,
}) {
  length ??= bitlengthInBytes(val);
  if (val == BigInt.zero) {
    return List.filled(length, 0, growable: true);
  }
  List<int> byteList = List<int>.filled(length, 0, growable: true);
  for (var i = 0; i < length; i++) {
    byteList[length - i - 1] = (val & BinaryOps.maskBig8).toInt();
    val = val >> 8;
  }

  if (order == Endian.little) {
    byteList = byteList.reversed.toList();
  }

  return byteList;
}