toBytes static method
Converts a BigInt to a list of bytes with the specified length and byte order.
The toBytes method takes a BigInt val
, a required length
parameter
representing the desired length of the resulting byte list, and an optional order
parameter (defaulting to big endian) specifying the byte order.
If the BigInt is zero, a list filled with zeros of the specified length is returned. Otherwise, the method converts the BigInt to a byte list, considering the specified length and byte order.
Example Usage:
BigInt value = BigInt.from(16909060);
`List<int>` byteList = BigIntUtils.toBytes(value, length: 4); // Result: [0x01, 0x02, 0x03, 0x04]
Parameters:
val
: The BigInt to be converted to a byte list.length
: The desired length of the resulting byte list.order
: The byte order to arrange the bytes in the resulting list (default is big endian). Returns: A list of bytes representing the BigInt with the specified length and byte order.
Implementation
static List<int> toBytes(BigInt val,
{required int length, Endian order = Endian.big}) {
if (val == BigInt.zero) {
return List.filled(length, 0);
}
final BigInt bigMaskEight = BigInt.from(0xff);
List<int> byteList = List<int>.filled(length, 0);
for (var i = 0; i < length; i++) {
byteList[length - i - 1] = (val & bigMaskEight).toInt();
val = val >> 8;
}
if (order == Endian.little) {
byteList = byteList.reversed.toList();
}
return List<int>.from(byteList);
}