Skip to content

Commit

Permalink
Implement ConvertBits
Browse files Browse the repository at this point in the history
A part of "Implement BIP173 addresses and tests"
  • Loading branch information
sipa authored and UdjinM6 committed Dec 25, 2020
1 parent 3ef0dce commit 34723e3
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/utilstrencodings.h
Original file line number Diff line number Diff line change
Expand Up @@ -159,4 +159,28 @@ bool TimingResistantEqual(const T& a, const T& b)
*/
bool ParseFixedPoint(const std::string &val, int decimals, int64_t *amount_out);

/** Convert from one power-of-2 number base to another. */
template<int frombits, int tobits, bool pad, typename O, typename I>
bool ConvertBits(O& out, I it, I end) {
size_t acc = 0;
size_t bits = 0;
constexpr size_t maxv = (1 << tobits) - 1;
constexpr size_t max_acc = (1 << (frombits + tobits - 1)) - 1;
while (it != end) {
acc = ((acc << frombits) | *it) & max_acc;
bits += frombits;
while (bits >= tobits) {
bits -= tobits;
out.push_back((acc >> bits) & maxv);
}
++it;
}
if (pad) {
if (bits) out.push_back((acc << (tobits - bits)) & maxv);
} else if (bits >= frombits || ((acc << (tobits - bits)) & maxv)) {
return false;
}
return true;
}

#endif // BITCOIN_UTILSTRENCODINGS_H

0 comments on commit 34723e3

Please sign in to comment.