Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page