convertBits function

Uint8List convertBits(
  1. Uint8List data,
  2. int from,
  3. int to, {
  4. bool strictMode = false,
})

Converts an array of integers made up of 'from' bits into an array of integers made up of 'to' bits. The output array is zero-padded if necessary, unless strict mode is true. Throws a ValidationError if input is invalid. Original by Pieter Wuille: https://github.com/sipa/bech32.

data Array of integers made up of 'from' bits. from Length in bits of elements in the input array. to Length in bits of elements in the output array. strictMode Require the conversion to be completed without padding.

Implementation

Uint8List convertBits(
  Uint8List data,
  int from,
  int to, {
  bool strictMode = false,
}) {
  final int length = strictMode
      ? ((data.length * from) ~/ to)
      : ((data.length * from + to - 1) ~/ to);
  final int mask = (1 << to) - 1;
  final Uint8List result = Uint8List(length);
  int index = 0;
  int accumulator = 0;
  int bits = 0;
  for (int i = 0; i < data.length; ++i) {
    final int value = data[i];
    validate(0 <= value && (value >> from) == 0, 'Invalid value: $value.');
    accumulator = (accumulator << from) | value;
    bits += from;
    while (bits >= to) {
      bits -= to;
      result[index] = (accumulator >> bits) & mask;
      ++index;
    }
  }
  if (!strictMode) {
    if (bits > 0) {
      result[index] = (accumulator << (to - bits)) & mask;
      ++index;
    }
  } else {
    validate(
      bits < from && ((accumulator << (to - bits)) & mask) == 0,
      'Input cannot be converted to $to bits without padding, but strict mode was used.',
    );
  }
  return result;
}