Why Long.toHexString(0xFFFFFFFF) returns ffffffffffffffff

前端 未结 4 676
無奈伤痛
無奈伤痛 2021-01-14 00:30

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

Long.toHexString(0xFFFFFFFF) returns ffffffffffffffff

Similarly, 0xFFFFFFFF

4条回答
  •  爱一瞬间的悲伤
    2021-01-14 00:52

    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"

提交回复
热议问题