简体   繁体   English

Java无法将十六进制字符串解析为int

[英]Java fails to parse a hex string as an int

Can someone tell me why this code throws an Exception? 有人可以告诉我为什么此代码引发异常吗?

int value = 0xabcdef01;
System.out.println(value);                 // prints -1412567295
String hex = Integer.toHexString(value);
System.out.println(hex);                   // prints abcdef01
// why does this line fail?
Integer.parseInt(hex, 16);  

This code throws the following exception: 此代码引发以下异常:

java.lang.NumberFormatException: For input string: "abcdef01"
  at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
  at java.lang.Integer.parseInt(Integer.java:583)

I'm running on Windows 7 with the following JDK 我在Windows 7上使用以下JDK运行

java version "1.8.0_51"
Java(TM) SE Runtime Environment (build 1.8.0_51-b16)
Java HotSpot(TM) 64-Bit Server VM (build 25.51-b03, mixed mode)

Perhaps what you wanted was 也许您想要的是

 int num = (int) Long.parseLong(hex, 16);  

The problem is that numbers >= 0x8000_0000 are too large to store in an int 问题是数字> = 0x8000_0000太大而无法存储在int

在使用Java 8时,请考虑Integer.parseUnsignedInt方法:

Integer.parseUnsignedInt(hex, 16);  

Your confusion about integer that doesn't go back to itself has to do with peculiarities of toHexString() which returns "abcdef01" rather than "-543210ff", which really represents your original integer. 您对不返回整数的整数的困惑与toHexString()的特殊性有关,该函数返回“ abcdef01”而不是“ -543210ff”,它实际上代表了您的原始整数。 Run this to see: 运行此命令以查看:

  int value = -0x543210ff;
  assert(value == 0xabcdef01);
  assert(value == Integer.parseInt("-543210ff", 16));

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

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