请解释输出。 Long.toHexString()

Please explain the output. Long.toHexString()

当我 运行 以下代码时:

class Solution{
public static void main(String []argh){
    System.out.println( Long.toHexString( Byte.MIN_VALUE ) );
    System.out.println( Long.toHexString( (byte)Math.pow(2,7) );
    System.out.println( Long.toHexString( Byte.MAX_VALUE ) );
    System.out.println( Long.toHexString( (byte)Math.pow(2,63) -1 ) );

    System.out.println();
    System.out.println();

    System.out.println( Long.toHexString( Short.MIN_VALUE ) );
    System.out.println( Long.toHexString( (short)Math.pow(2,15) );
    System.out.println( Long.toHexString( Short.MAX_VALUE ) );
    System.out.println( Long.toHexString( (short)Math.pow(2,15) -1 ) );

    System.out.println();
    System.out.println();

    System.out.println( Long.toHexString( Integer.MIN_VALUE ) );
    System.out.println( Long.toHexString( (-1*(int)Math.pow(2,31)) ) );
    System.out.println( Long.toHexString( Integer.MAX_VALUE ) );
    System.out.println( Long.toHexString( (int)Math.pow(2,31) -1 ) );

    System.out.println();
    System.out.println();

    System.out.println( Long.toHexString( Long.MIN_VALUE ) );
    System.out.println( Long.toHexString( (-1*(long)Math.pow(2,63)) ) );
    System.out.println( Long.toHexString( Long.MAX_VALUE ) );
    System.out.println( Long.toHexString( (long)Math.pow(2,63) -1 ) );

    }
}

我得到以下输出:

ffffffffffffff80
80
7f
fffffffffffffffe

ffffffffffff8000
8000
7fff
ffffffffffff7fff

ffffffff80000000
ffffffff80000001
7fffffff
7ffffffe

8000000000000000
8000000000000001
7fffffffffffffff
7ffffffffffffffe

有人可以解释一下为什么 HexString 的长度不同吗?我知道这是基本的,请也解释一下答案。我很困惑。

编辑|对不起,我被这个愚蠢的事情弄糊涂了,我没有试着去想。

这是因为它不包括前面的零。

例如Byte.MAX_VALUE为127,表示为“7f”。它可以 return 表示为“000000000000007F”,但设计师一定已经决定,如果没有初始零,会有更多人想要它。

您可以看到记录了此行为 here

This value is converted to a string of ASCII digits in hexadecimal (base 16) with no extra leading 0s.

强调我的。

在评论中,您似乎对为什么 MIN_VALUE 长度这么长感到困惑。为了解释这一点,请考虑 Byte.MIN_VALUEBYTE.MAX_VALUEByte.MIN_VALUE 是 -128,Byte.MAX_VALUE 是 127。由于您将这些传递给 Long.toHexString,它期望将 long 作为其参数,因此 它们会向上转换为longs。因此,最终被转换为十六进制字符串的值是 -128 和 127 的 long 值,它们分别使用 Two's Complement 表示为 "ffffffffffffff80" 和“7f”。