使用 toHexString 解析 Long 时如何删除前导 "f"
How to remove leading "f" when parsing Long using toHexString
我正在为我的项目编写单元测试,试图使用方法 Long.toHexString(l)
检查十六进制字符串格式的 long
的值。
当我使用 long
等于 111
进行测试时,我得到的值 6f
是正确的,正如我预期的那样。
但是当 long 为 -64
时,我期望 c0
但相反,我得到 ffffffffffffffc0
。
通过阅读 Java 文档,我可以看到该方法需要一个 unsigned long,如果它传递了一个负值,那么 returns 2s 补码。但是如何纠正呢?
我写了一个小的单元测试程序来演示,
@Test
public void long_to_hex() {
Long l = new Long(-64);
//Long l = new Long(111);
System.out.println(l.toHexString(l));
}
您的陈述“如果它传递了一个负值,则 returns 2 的补码”与 the documentation:
不匹配
The unsigned long value is the argument plus 2⁶⁴ if the argument is negative; otherwise, it is equal to the argument.
所以它实际上是相反的,你传入的值已经使用了 2s 补码,但返回值是一个字符串,即使不被解释为 2s 补码,也能够再现正确的 long
位。换句话说,在您的 long
值中,所有高位都已设置,因此,十六进制表示具有相应数量的前导 f
字符。
另一种方法是保持表示签名:
long l = -64;
System.out.println(Long.toHexString(l));
System.out.println(Long.toString(l, 16));
ffffffffffffffc0
-40
我正在为我的项目编写单元测试,试图使用方法 Long.toHexString(l)
检查十六进制字符串格式的 long
的值。
当我使用 long
等于 111
进行测试时,我得到的值 6f
是正确的,正如我预期的那样。
但是当 long 为 -64
时,我期望 c0
但相反,我得到 ffffffffffffffc0
。
通过阅读 Java 文档,我可以看到该方法需要一个 unsigned long,如果它传递了一个负值,那么 returns 2s 补码。但是如何纠正呢?
我写了一个小的单元测试程序来演示,
@Test
public void long_to_hex() {
Long l = new Long(-64);
//Long l = new Long(111);
System.out.println(l.toHexString(l));
}
您的陈述“如果它传递了一个负值,则 returns 2 的补码”与 the documentation:
不匹配The unsigned long value is the argument plus 2⁶⁴ if the argument is negative; otherwise, it is equal to the argument.
所以它实际上是相反的,你传入的值已经使用了 2s 补码,但返回值是一个字符串,即使不被解释为 2s 补码,也能够再现正确的 long
位。换句话说,在您的 long
值中,所有高位都已设置,因此,十六进制表示具有相应数量的前导 f
字符。
另一种方法是保持表示签名:
long l = -64;
System.out.println(Long.toHexString(l));
System.out.println(Long.toString(l, 16));
ffffffffffffffc0
-40