11.19. Performing Arithmetic on Bitsets

Problem

You want to perform basic arithmetic and comparison operations on a set of bits as if it were a binary representation of an unsigned integer number.

Solution

The functions in Example 11-36 provide functions that allow arithmetic and comparison of bitset class template from the <bitset> header as if it represents an unsigned integer.

Example 11-36. bitset_arithmetic.hpp

#include <stdexcept> #include <bitset> bool fullAdder(bool b1, bool b2, bool& carry) { bool sum = (b1 ^ b2) ^ carry; carry = (b1 && b2) || (b1 && carry) || (b2 && carry); return sum; } bool fullSubtractor(bool b1, bool b2, bool& borrow) { bool diff; if (borrow) { diff = !(b1 ^ b2); borrow = !b1 || (b1 && b2); } else { diff = b1 ^ b2; borrow = !b1 && b2; } return diff; } template<unsigned int N> bool bitsetLtEq(const std::bitset<N>& x, const std::bitset<N>& y) { for (int i=N-1; i >= 0; i--) { if (x[i] && !y[i]) return false; if (!x[i] && y[i]) return true; } return true; } template<unsigned int N> bool bitsetLt(const std::bitset<N>& x, const std::bitset<N>& y) { for (int i=N-1; i >= 0; i--) { if (x[i] && !y[i]) return false; if (!x[i] && y[i]) return true; } return false; } template<unsigned int N> bool bitsetGtEq(const std::bitset<N>& x, const std::bitset<N>& y) { for (int i=N-1; i >= 0; i--) { if (x[i] && !y[i]) return true; if (!x[i] && y[i]) return false; } return true; } template<unsigned int N> bool bitsetGt(const std::bitset<N>& x, const std::bitset<N>& y) { for (int ...

Get C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.