Poperton
Poperton

Reputation: 2148

how to set a long value in java to 2^64-1?

Java doesn't have support for unsigned integers but if you treat the longs 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

Answers (1)

Anonymous
Anonymous

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:

  1. For readers who know that a long is 64 bits and are comfortable with hexadecimal numbers it’s easier to read than 18446744073709551615.
  2. It doesn’t give the reader the impression that the number should be understood as a negative number (no matter that Jon Skeet is of course correct that it is negative).

Upvotes: 2

Related Questions