Java equivalent of unsigned long long?

我是研究僧i 提交于 2019-11-26 18:25:18
Sean Bright

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.

Paul Tomblin

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:

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!