简体   繁体   English

java:Long.parseLong(s,16)和Long.toHexString(l)不反转?

[英]java: Long.parseLong(s,16) and Long.toHexString(l) not inverses?

I get this but yet I don't get it: 我得到了这个,但我没有得到它:

package com.example.bugs;

public class ParseLongTest {
    public static void main(String[] args) {
        long l = -1;
        String s = Long.toHexString(l);
        System.out.println(s);
        long l2 = Long.parseLong(s, 16);
    }   
}

This fails with the following: 这失败了以下内容:

ffffffffffffffff
Exception in thread "main" java.lang.NumberFormatException: For input string: "ffffffffffffffff"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
    at java.lang.Long.parseLong(Long.java:410)
    at java.lang.Long.parseLong(Long.java:468)
    at com.example.bugs.ParseLongTest.main(ParseLongTest.java:8)

presumably because if you literally interpreted 0xffffffffffffffffL, it would not fit in the Long number space, which is signed. 大概是因为如果你从字面上解释为0xffffffffffffffffL,它就不适合签名的Long数字空间。

But why does Long.toHexString() produce a string that cannot be parsed by Long.parseLong(), and how do I work around this? 但是为什么Long.toHexString()会产生一个无法通过Long.parseLong()解析的字符串,我该如何解决这个问题呢? (I need a way of getting long values to their hex string representation, and back again) (我需要一种方法来获取十六进制字符串表示的长值,然后再返回)

Long.parseLong(String s, int radix) doesn't understand two's complement. Long.parseLong(String s, int radix)不理解二进制补码。 For negative number it expects minus sign. 对于负数,它预期减号。 As bestsss already mentioned you should use Long.toString(long l, int radix) to make hex string compatible with this parsing method. 正如已经提到的那样,你应该使用Long.toString(long l, int radix)来使十六进制字符串与这种解析方法兼容。

这是一个已知的错误,它在1.8中已修复,请参阅http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4215269

如果Java 1.8不是选项UnsignedLongs.parseUnsignedLong(String s, int radix)可以使用guava的UnsignedLongs.parseUnsignedLong(String s, int radix)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM