在java中从十六进制转换为int

时间:2012-05-21 07:49:14

标签: java hex int

由于以下代码行,我收到错误:

int x = color(Integer.parseInt("ffffffde",16));

我认为可能是因为它是负值

任何想法为什么或如何或如何解决它?

编辑:

抱歉,没有包含实际错误。这是:

  

例外   线程“动画线程”java.lang.NumberFormatException:用于输入   string:“ffffffde”at   java.lang.NumberFormatException.forInputString(未知来源)at   java.lang.Integer.parseInt(未知来源)

编辑2:

通过以下代码创建值(“ffffffde”):

Integer.toHexString(int_val);

编辑3: 事实证明这是一个已知的错误(http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4215269) 虽然您可以将整数转换为十六进制字符串,但如果它们是负数,则无法将它们转换回来!!

2 个答案:

答案 0 :(得分:11)

ffffffde大于整数最大值

  

Java int is 32 bit签名类型的范围从-2,147,483,648到2,147,483,647。

ffffffde = 4,294,967,262 

修改

您使用Integer.toHexString(int_val)将int转换为十六进制字符串。从该方法的文档:

  

返回整数参数的字符串表示形式,作为基数为16的无符号整数。

int签名类型。

使用

int value = new BigInteger("ffffffde", 16).intValue();

将其作为负值取回。

答案 1 :(得分:5)

如果您收到这样的错误,

Exception in thread "main" java.lang.NumberFormatException: For input string: "ffffffde"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
    at java.lang.Integer.parseInt(Integer.java:461)
    at com.TestStatic.main(TestStatic.java:22)

然后你传递的价值存在问题 ffffffde 。这不是解析为int的有效十六进制值。

请试试这个

int x = Integer.parseInt("ffffde",16);
        System.out.println(x);

它应该有用。

对于十六进制值,您需要解析为

Long x = Long.parseLong("ffffffde",16);
        System.out.println(x);

这也应该有用