convert method

List<int> convert(
  1. List<int> data,
  2. int from,
  3. int to,
  4. bool pad,
)

Implementation

List<int> convert(List<int> data, int from, int to, bool pad) {
  var acc = 0;
  var bits = 0;
  var result = <int>[];
  var maxv = (1 << to) - 1;

  for (var v in data) {
    if (v < 0 || (v >> from) != 0) {
      throw Exception();
    }
    acc = (acc << from) | v;
    bits += from;
    while (bits >= to) {
      bits -= to;
      result.add((acc >> bits) & maxv);
    }
  }

  if (pad) {
    if (bits > 0) {
      result.add((acc << (to - bits)) & maxv);
    }
  } else if (bits >= from) {
    throw InvalidPadding('Excess padding');
  } else if (((acc << (to - bits)) & maxv) != 0) {
    throw InvalidPadding('Non-zero padding');
  }

  return result;
}