Why Long.toHexString(0xFFFFFFFF) returns ffffffffffffffff

南笙酒味 提交于 2020-05-27 06:16:06

问题


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.


回答1:


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




回答2:


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)



回答3:


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

However, if the number were unsigned, the string would also be ffffffff [but there's no unsigned in java].




回答4:


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

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

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

long literals are post-fixed by an L. So your expected behaviour is written in Java as:

Long.toHexString(0xFFFFFFFFL)

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



来源:https://stackoverflow.com/questions/9065727/why-long-tohexstring0xffffffff-returns-ffffffffffffffff

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!