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

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