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) not equal.

+4
source share
4 answers

As others have said, 0xFFFFFFFF evaluates to int -1 , which advances to long .

To get the expected result, specify a constant with the suffix L to indicate that it should be considered as long , i.e. Long.toHexString(0xFFFFFFFFL) .

+6
source

It:

 Long.toHexString(0xFFFFFFFF) 

is equivalent to:

 Long.toHexString(-1) 

which is equivalent to:

 Long.toHexString(0xFFFFFFFFFFFFFFFFL) 

Basically the problem is that you specify a negative int value, which then converts to an equivalent negative long value, which consists of "all Fs". If you really want 8 Fs, you should use:

 Long.toHexString(0xFFFFFFFFL) 
+9
source

Of course, Long in java is a 64-bit long! 0xFFFFFFFF means -1 as int , when it is written in 64 bits, it is ffffffffffffffff .

However, if the number was unsigned, the string would also be ffffffff [but there is no unsigned in java].

+2
source

0xFFFFFFFF is an int literal. When using int (32 bits in Java) 0xFFFFFFFF is -1 . What does your code do:

  • the compiler parses 0xFFFFFFFF as an int with a value of -1
  • java runtime calls Long.toHexString(-1) ( -1 gets "casted" automatically in long , which is expected here)

And when using long (64 bit in Java) -1 is 0xffffffffffffffff .

long literals are postfixed with L So your expected behavior is written in Java as:

 Long.toHexString(0xFFFFFFFFL) 

and Long.toHexString(0xFFFFFFFFL) is "ffffffff"

+1
source

Source: https://habr.com/ru/post/1393782/


All Articles