Use of 128-Bit Integer in C++

In this tutorial, we will discuss 128-bit integers in C++. We will also see why we need it and the possible alternatives in C++.

Use of 128-Bit Integer in C++

We have multiple choices to handle integers in C++. Starting from int data type to long, long int, and long long int that has 64-bits and the maximum positive number that we can store is 9223372036854775807 (in hexadecimal 7FFFFFFFFFFFFFFF).

Consider 7 in hexadecimal number; next, we will have 8, having binary 1000, which means the sign bit is on. Finally, we have negative integers from -1 to -9223372036854775808.9223372036854775807 is a number big enough to handle many storage plus arithmetic operations requirements.

Importance of 128-Bit Integer & Its Alternatives in C++

Now, if you need even bigger integers, the question is, do we want to perform arithmetic operations on those integers? If the answer is yes, you might probably need more storage than 128-bits.

The result of the addition or multiplication of two big integers might need more bits. Therefore, in this case, implementing big integers might help you.

Lastly, if you need a 128-bit integer for storage only, one solution is to create a structure of two 64-bit integers, or you might take an int array of 8 elements or a char array of 16 elements.

However, GCC does provide a specific data type for 128-bit integers that is int128_t; on supported compilers, you can check the size:

int128_t var;
cout << sizeof(var) << '\n';

The output will be 16, which means 16x8=128 bits.

However, it is supported for specific processors, which are capable of holding 128-bits; otherwise, when you try to store a big integer, the compiler generates one of the following warnings:

 warning: overflow in implicit constant conversion
 warning: integer constant is too large for its type

The conclusion of the discussion is to decide precisely how many bits will be required in the worst case.

Further, do you want to store data only, or do you want to perform arithmetic operations? Then, Big Integer implementation is your solution if you want to perform arithmetic operations.

In the case of Big Integer implementation, you don’t have to worry about even 500 or 5000 bits.

If you want to do storage only, you have other solutions available. Use structure of two, 64-bits data members, or use array of int data type or char data type.

Related Article - C++ Integer

  • Big Integer in C++
  • Specify 64-Bit Integer in C++
  • Comparison Between Signed and Unsigned Integer Expressions in C++