convertBits function

List<int> convertBits(
  1. List<int> data,
  2. int fromWidth,
  3. int toWidth,
  4. bool pad
)

Implementation

List<int> convertBits(List<int> data, int fromWidth, int toWidth, bool pad) {
  int acc = 0;
  int bits = 0;
  int maxv = (1 << toWidth) - 1;
  List<int> ret = [];

  for (int i = 0; i < data.length; i++) {
    int value = data[i] & 0xff;
    if (value < 0 || value >> fromWidth != 0) {
      throw FormatException("input data bit-width exceeds $fromWidth: $value");
    }
    acc = (acc << fromWidth) | value;
    bits += fromWidth;
    while (bits >= toWidth) {
      bits -= toWidth;
      ret.add((acc >> bits) & maxv);
    }
  }

  if (pad) {
    if (bits > 0) {
      ret.add((acc << (toWidth - bits)) & maxv);
    } else if (bits >= fromWidth || ((acc << (toWidth - bits)) & maxv) != 0) {
      throw FormatException("input data bit-width exceeds $fromWidth: $bits");
    }
  }

  return ret;
}