| 32 | /** Convert from one power-of-2 number base to another. */ |
| 33 | template<int frombits, int tobits, bool pad> |
| 34 | bool convertbits(segwit_data& out, const segwit_data& in) { |
| 35 | int acc = 0; |
| 36 | int bits = 0; |
| 37 | const int maxv = (1 << tobits) - 1; |
| 38 | const int max_acc = (1 << (frombits + tobits - 1)) - 1; |
| 39 | for (size_t i = 0; i < in.size(); ++i) { |
| 40 | int value = in[i]; |
| 41 | acc = ((acc << frombits) | value) & max_acc; |
| 42 | bits += frombits; |
| 43 | while (bits >= tobits) { |
| 44 | bits -= tobits; |
| 45 | out.push_back((acc >> bits) & maxv); |
| 46 | } |
| 47 | } |
| 48 | if (pad) { |
| 49 | if (bits) out.push_back((acc << (tobits - bits)) & maxv); |
| 50 | } else if (bits >= frombits || ((acc << (tobits - bits)) & maxv)) { |
| 51 | return false; |
| 52 | } |
| 53 | return true; |
| 54 | } |
| 55 | |
| 56 | } // namespace |
| 57 | |