encodeBigInt function
Encode a BigInt into a Uint8List. This function takes a BigInt integer and encodes it into a Uint8List representation, considering necessary padding and byte order.
Implementation
Uint8List encodeBigInt(BigInt number) {
int needsPaddingByte;
int rawSize;
/// Determine the raw size of the encoding and whether a padding byte is needed.
if (number > BigInt.zero) {
rawSize = (number.bitLength + 7) >> 3;
needsPaddingByte =
((number >> (rawSize - 1) * 8) & BigInt.from(0x80)) == BigInt.from(0x80)
? 1
: 0;
/// Ensure that a padding byte is added if the raw size is less than 32 bytes.
if (rawSize < 32) {
needsPaddingByte = 1;
}
} else {
needsPaddingByte = 0;
rawSize = (number.bitLength + 8) >> 3;
}
/// Calculate the final size of the Uint8List.
final size = rawSize < 32 ? rawSize + needsPaddingByte : rawSize;
/// Initialize the result Uint8List.
var result = Uint8List(size);
/// Encode the BigInt into the Uint8List while considering byte order.
for (int i = 0; i < size; i++) {
result[size - i - 1] = (number & BigInt.from(0xff)).toInt();
number = number >> 8;
}
return result;
}