Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Long.toHexString(0xFFFFFFFF) returns ffffffffffffffff

This is what I see in java, and it puzzles me.

Long.toHexString(0xFFFFFFFF) returns ffffffffffffffff

Similarly, 0xFFFFFFFF and Long.parseLong("FFFFFFFF", 16) are unequal.

like image 839
Vic Avatar asked Nov 30 '22 03:11

Vic


2 Answers

This:

Long.toHexString(0xFFFFFFFF)

is equivalent to:

Long.toHexString(-1)

which is equivalent to:

Long.toHexString(0xFFFFFFFFFFFFFFFFL)

Basically, the problem is that you're specifying a negative int value, which is then being converted to the equivalent negative long value, which consists of "all Fs". If you really want 8 Fs, you should use:

Long.toHexString(0xFFFFFFFFL)
like image 44
Jon Skeet Avatar answered Dec 01 '22 15:12

Jon Skeet


As others have said, 0xFFFFFFFF evaluates to the int value -1, which is promoted to a long.

To get the result you were expecting, qualify the constant with the L suffix to indicate it should be treated as a long, i.e. Long.toHexString(0xFFFFFFFFL).

like image 143
Graham Borland Avatar answered Dec 01 '22 17:12

Graham Borland