Skip to content

Representing 128-bit numbers in C++

An answer to this question on Stack Overflow.

Question

What's the best way to represent a 128-bit number in C++? It should behave as closely to the built-in numeric types as possible (i.e. support all the arithmetic operators, etc).

I was thinking of building a class that had 2 64 bit or 4 32 bit numbers. Or possibly just creating a 128 bit block of memory and doing everything myself.

Is there some easier/more standard way, or something that I'm less likely to screw up when implementing it myself? :)

It would also be nice if it could be extended to 256-bit, 512-bit, etc...

Answer

GCC supports a 128-bit integer type for processors which support it. You can access it using:

__int128          a;
unsigned __int128 b;

02020-02-10 Update: according to this: GCC, Clang, and Intel ICC all support a built-in __int128 type.