Inside Bitcoin
Opening the selected file…
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2018-present The Bitcoin Core developers2// Distributed under the MIT software license, see the accompanying3// file COPYING or http://www.opensource.org/licenses/mit-license.php.5#ifndef BITCOIN_UTIL_GOLOMBRICE_H6#define BITCOIN_UTIL_GOLOMBRICE_H8#include <util/fastrange.h>10#include <streams.h>12#include <cstdint>14template <typename OStream>15void GolombRiceEncode(BitStreamWriter<OStream>& bitwriter, uint8_t P, uint64_t x)16{17// Write quotient as unary-encoded: q 1's followed by one 0.18uint64_t q = x >> P;19while (q > 0) {20int nbits = q <= 64 ? static_cast<int>(q) : 64;21bitwriter.Write(~0ULL, nbits);22q -= nbits;23}24bitwriter.Write(0, 1);26// Write the remainder in P bits. Since the remainder is just the bottom27// P bits of x, there is no need to mask first.28bitwriter.Write(x, P);29}31template <typename IStream>32uint64_t GolombRiceDecode(BitStreamReader<IStream>& bitreader, uint8_t P)33{34// Read unary-encoded quotient: q 1's followed by one 0.35uint64_t q = 0;36while (bitreader.Read(1) == 1) {37++q;38}40uint64_t r = bitreader.Read(P);42return (q << P) + r;43}45#endif // BITCOIN_UTIL_GOLOMBRICE_H