toBytes static method

List<int> toBytes(
  1. int val, {
  2. required int length,
  3. Endian byteOrder = Endian.big,
  4. int maxBytesLength = 6,
})

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,
    int maxBytesLength = 6}) {
  assert(maxBytesLength > 0 && maxBytesLength <= 8);
  assert(length <= maxBytesLength);
  if (length > 4) {
    int lowerPart = val & mask32;
    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;
  }
  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;
}