convertBits function
Converts data from "from" bits to "to" bits with optional padding
(pad). Returns the new data or null if conversion was not possible.
Used to convert to and from the 5-bit words for bech32.
Implementation
List<int>? convertBits(List<int> data, int from, int to, bool pad) {
var acc = 0;
var bits = 0;
List<int> result = [];
final maxv = (1 << to) - 1;
for (final v in data) {
if (v < 0 || (v >> from) != 0) return null;
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 || ((acc << (to - bits)) & maxv) != 0) {
return null;
}
return result;
}