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?
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.
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);
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 BigInteger
.
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.
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.
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.
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.
Java does not have unsigned types. As already mentioned, incure the overhead of BigInteger or use JNI to access native code.
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>
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.
来源:https://stackoverflow.com/questions/508630/java-equivalent-of-unsigned-long-long