问题
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?
回答1:
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.
回答2:
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);
回答3:
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.
回答4:
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.
回答5:
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.
回答6:
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.
回答7:
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.
回答8:
Java does not have unsigned types. As already mentioned, incure the overhead of BigInteger or use JNI to access native code.
回答9:
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>
回答10:
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