toBytes static method
Converts an integer to a byte list with the specified length and endianness.
If the length
is not provided, it is calculated based on the bit length
of the integer, ensuring minimal byte usage. The byteOrder
determines
whether the most significant bytes are at the beginning (big-endian) or end
(little-endian) of the resulting byte list.
Implementation
static List<int> toBytes(int val,
{required int length, Endian byteOrder = Endian.big}) {
assert(length <= 8);
if (length > 4) {
final int lowerPart = val & mask32;
final int upperPart = (val >> 32) & mask32;
final bytes = [
...toBytes(upperPart, length: length - 4),
...toBytes(lowerPart, length: 4),
];
if (byteOrder == Endian.little) {
return bytes.reversed.toList();
}
return bytes;
}
final List<int> byteList = List<int>.filled(length, 0);
for (var i = 0; i < length; i++) {
byteList[length - i - 1] = val & mask8;
val = val >> 8;
}
if (byteOrder == Endian.little) {
return byteList.reversed.toList();
}
return byteList;
}