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.20. Representing Large Fixed-Width Integers

Problem

You need to perform arithmetic of numbers larger than can be represented by a long int.

Solution

The BigInt template in Example 11-38 uses the bitset from the <bitset> header to allow you to represent unsigned integers using a fixed number of bits specified as a template parameter.

Example 11-38. big_int.hpp

#ifndef BIG_INT_HPP
#define BIG_INT_HPP

#include <bitset>

#include "bitset_arithmetic.hpp" // Recipe 11.20 template<unsigned int N> class BigInt { typedef BigInt self; public: BigInt() : bits() { } BigInt(const self& x) : bits(x.bits) { } BigInt(unsigned long x) { int n = 0; while (x) { bits[n++] = x & 0x1; x >>= 1; } } explicit BigInt(const std::bitset<N>& x) : bits(x) { } // public functions bool operator[](int n) const { return bits[n]; } unsigned long toUlong() const { return bits.to_ulong(); } // operators self& operator<<=(unsigned int n) { bits <<= n; return *this; } self& operator>>=(unsigned int n) { bits >>= n; return *this; } self operator++(int) { self i = *this; operator++(); return i; } self operator--(int) { self i = *this; operator--(); return i; } self& operator++() { bool carry = false; bits[0] = fullAdder(bits[0], 1, carry); for (int i = 1; i < N; i++) { bits[i] = fullAdder(bits[i], 0, carry); } return *this; } self& operator--() { bool borrow = false; bits[0] = fullSubtractor(bits[0], 1, borrow); for (int i = 1; i < N; i++) { bits[i] = fullSubtractor(bits[i], 0, borrow); } return *this; } self& operator+=(const ...
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