...one of the most highly
regarded and expertly designed C++ library projects in the
world.
— Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
In this example we'll show how individual bits within an integer may be manipulated, we'll start with an often needed calculation of 2n - 1, which we could obviously implement like this:
using boost::multiprecision::cpp_int; cpp_int b1(unsigned n) { cpp_int r(1); return (r << n) - 1; }
Calling:
std::cout << std::hex << std::showbase << b1(200) << std::endl;
Yields as expected:
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
However, we could equally just set the n'th bit in the result, like this:
cpp_int b2(unsigned n) { cpp_int r(0); return --bit_set(r, n); }
Note how the bit_set
function sets the specified bit in its argument and then returns a reference
to the result - which we can then simply decrement. The result from a
call to b2
is the same
as that to b1
.
We can equally test bits, so for example the n'th bit of the result returned
from b2
shouldn't be
set unless we increment it first:
assert(!bit_test(b1(200), 200)); // OK assert(bit_test(++b1(200), 200)); // OK
And of course if we flip the n'th bit after increment, then we should get back to zero:
assert(!bit_flip(++b1(200), 200)); // OK