简体   繁体   中英

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

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

在使用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. Run this to see:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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