Is it possible to have a 128bit integer in Java or C++?
-
2You need to be more specific about the requirements you have. Just representing should be obviously possible: long a, b represents a 128-bit number as a pair of 64-bit ones. – unwind Jun 28 '10 at 12:19
-
1@unwind: long might be 32 bits on some compilers. `__int64` or `long long` will be at minimum 64 bits, but are non-standard extensions. – Brian Jun 28 '10 at 13:45
-
possible duplicate of [big integers in c++](http://stackoverflow.com/questions/1815803/big-integers-in-c) – MSalters Jun 28 '10 at 14:17
-
1@Brian: correct, when I answered I was pretty sure this question was about Java only. For C++, use four uint32_t parts. – unwind Jun 28 '10 at 14:57
-
in g++ you can use these builtin types (at least on 64bits platforms): `__int128_t` and `__uint_128_t`. – rafak Jul 01 '10 at 08:51
6 Answers
Of course you can represent them.
At least you can use a byte-array with 16 elements.
However, the question is if you just want to represent the value or actually do some calculations with it.
In Java you can use BigInteger
to represent (effectively) arbitrary sized integer values and do calculations as well.

- 302,674
- 57
- 556
- 614
-
C/C++ already has __int 128 https://gnu.huihoo.org/gcc/gcc-4.7.4/gcc/_005f_005fint128.html. U can use BigInteger for Byte with the same success. There are processors that support 128-bit values, and there are use-cases that use such numbers broadly like GUID or IPv6. – user9999 Dec 07 '20 at 23:09
-
here is an answer which clarifies modern commodity CPUs capabilities https://stackoverflow.com/a/37925245/6713531. And here is Rust https://stackoverflow.com/questions/57340308/how-does-rusts-128-bit-integer-i128-work-on-a-64-bit-system – user9999 Dec 07 '20 at 23:35
In Java, you can use the BigInteger class to store arbitrarily large integers. In C++ you can use a library like GMP to get the same functionality.
You can. You will most likely need to use a library to do this though, at least for C++.
I like the PolarSSL library or the GNU MP Bignum library.

- 56,849
- 55
- 141
- 195
The BigInteger
class is designed for integer values bigger then Long.MAX_VALUE
.

- 113,398
- 19
- 180
- 268
java.math.BigInteger
To work with integers that are larger than 64 bits (the size of a long), use java.math.BigInteger. This class represents unbounded integers and provides a number of methods for doing arithmetic with them.
http://leepoint.net/notes-java/data/numbers/10biginteger.html
If you need decimal values use BigDecimal

- 800
- 7
- 11
Of course, you can use BigInteger class in java.math package. This class provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation like operations.
This class has been added in JDK1.1 itself.
But I don't know there is such a availability built into with C++ library. There can be a extensible API from third parties.

- 2,604
- 6
- 26
- 36