padBytesLeft static method

List<int> padBytesLeft(
  1. List<int> bytes,
  2. int length
)

Left-pads a byte array with zeros to ensure it is exactly length bytes long.

  • If bytes is already length bytes or longer, it will be returned.
  • If bytes is shorter than length, zeros will be added to the beginning (left-side).

Implementation

static List<int> padBytesLeft(List<int> bytes, int length) {
  // If the input is already the desired length or longer, keep the last [length] bytes.
  if (bytes.length >= length) {
    return bytes;
  }

  // Otherwise, create a new list filled with zeros.
  final result = List<int>.filled(length, 0);

  // Calculate where to start placing the original bytes.
  final start = length - bytes.length;

  // Copy the original bytes into the end of the result.
  result.setRange(start, length, bytes);

  return result;
}