ConvertBits() - convert from one power-of-2 number base to another.

Function extracted from upstream:
  PR bitcoin/bitcoin#11167
  Commit c091b99379b97cb314c9fa123beabdbc324cf7a4
This commit is contained in:
Jack Grigg
2018-06-07 12:41:05 +12:00
parent 7e45636707
commit 6b759fb092
3 changed files with 77 additions and 0 deletions

View File

@@ -133,4 +133,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