Java equivalent of unsigned long long?
JavaUnsignedPrimitiveUnsigned Long-Long-IntJava Problem Overview
In C++, I enjoyed having access to a 64 bit unsigned integer, via unsigned long long int
, or via uint64_t
. Now, in Java longs are 64 bits, I know. However, they are signed.
Is there an unsigned long (long) available as a Java primitive? How do I use it?
Java Solutions
Solution 1 - Java
Starting Java 8, there is support for unsigned long (unsigned 64 bits). The way you can use it is:
Long l1 = Long.parseUnsignedLong("17916881237904312345");
To print it, you can not simply print l1, but you have to first:
String l1Str = Long.toUnsignedString(l1)
Then
System.out.println(l1Str);
Solution 2 - Java
I don't believe so. Once you want to go bigger than a signed long, I think BigInteger is the only (out of the box) way to go.
Solution 3 - Java
Nope, there is not. You'll have to use the primitive long
data type and deal with signedness issues, or use a class such as http://java.sun.com/javase/6/docs/api/java/math/BigInteger.html">`BigInteger`</a>;.
Solution 4 - Java
No, there isn't. The designers of Java are on record as saying they didn't like unsigned ints. Use a BigInteger instead. See this question for details.
Solution 5 - Java
Java 8 provides a set of unsigned long operations that allows you to directly treat those Long variables as unsigned Long, here're some commonly used ones:
- String toUnsignedString(long i)
- int compareUnsigned(long x, long y)
- long divideUnsigned(long dividend, long divisor)
- long remainderUnsigned(long dividend, long divisor)
And additions, subtractions, and multiplications are the same for signed and unsigned longs.
Solution 6 - Java
Depending on the operations you intend to perform, the outcome is much the same, signed or unsigned. However, unless you are using trivial operations you will end up using BigInteger.
Solution 7 - Java
For unsigned long you can use UnsignedLong class from Guava library:
It supports various operations:
- plus
- minus
- times
- mod
- dividedBy
The thing that seems missing at the moment are byte shift operators. If you need those you can use BigInteger from Java.
Solution 8 - Java
Java does not have unsigned types. As already mentioned, incure the overhead of BigInteger or use JNI to access native code.
Solution 9 - Java
The org.apache.axis.types package has a
UnsignedLong class.
for maven:
<dependency>
<groupId>org.apache.axis</groupId>
<artifactId>axis</artifactId>
<version>1.4</version>
</dependency>
Solution 10 - Java
Seems like in Java 8 some methods are added to Long to treat old good [signed] long as unsigned. Seems like a workaround, but may help sometimes.