## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

No credit card required

# 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 ...`

## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

No credit card required