Reputation: 2148
Java doesn't have support for unsigned integers but if you treat the long
s as unsigned, you can do multiplications just fine.
But what is the best way to set a long
from 2^63+1
to 2^64-1
?
Long.MAX_VALUE
is 0x7fffffffffffffffL
;
The only way I know is
long maximumUnsigned = new BigInteger("18446744073709551615").longValue()
(where is 18446744073709551615 = 2^64-1
)
Doing long maximumUnsigned = -1
would work also but I find this problematic and could trick the readers into thinking it's negative.
Upvotes: 0
Views: 654
Reputation: 86276
There doesn’t seem to be a perfect solution. Since, as you say, Long.MAX_VALUE
is 0x7fffffffffffffffL
, I think I’d just put an F
in the first position too:
long maxUnsignedLong = 0xFFFF_FFFF_FFFF_FFFFL;
System.out.println(Long.toUnsignedString(maxUnsignedLong));
Output:
18446744073709551615
Advantages:
long
is 64 bits and are comfortable with hexadecimal numbers it’s easier to read than 18446744073709551615.Upvotes: 2