toByteArray function

Uint8List toByteArray(
  1. int value, {
  2. int length = 0,
})

Convert any number into a byte array

Implementation

Uint8List toByteArray(int value, {int length = 0}) {
  final byteMask = BigInt.from(0xff);
  var number = BigInt.from(value);
  // Not handling negative numbers. Decide how you want to do that.
  int size;
  if (length > 0) {
    size = length;
  } else {
    size = (number.bitLength + 7) >> 3;
  }
  if (size == 0) {
    return Uint8List.fromList(<int>[0]);
  }

  // ignore: prefer_final_locals
  var result = Uint8List(size);
  for (var i = 0; i < size; i++) {
    result[size - i - 1] = (number & byteMask).toInt();
    number = number >> 8;
  }
  return result;
}