Unsigned long in Java

Annapoorni D picture Annapoorni D · Jun 7, 2017 · Viewed 44.8k times · Source

Currently, I am using signed values, -2^63 to 2^63-1. Now I need the same range (2 * 2^64), but with positive values only. I found the java documentations mentioning unsigned long, which suits this use.

I tried to declare 2^64 to a Long wrapper object, but it still loses the data, in other words, it only captures till the Long.MAX_VALUE, so I am clearly missing something. Is BigInteger the signed long that Java supports?

Is there a definition or pointer as to how to declare and use it?

Answer

xenteros picture xenteros · Jun 7, 2017

In Java 8, unsigned long support was introduced. Still, these are typical longs, but the sign doesn't affect adding and subtracting. For dividing and comparing, you have dedicated methods in Long. Also, you can do the following:

long l1 = Long.parseUnsignedLong("12345678901234567890");
String l1Str = Long.toUnsignedString(l1)

BigInteger is a bit different. It can keep huge numbers. It stores them as int[] and supports arithmetic.