简体   繁体   English

为什么 Integer.valueOf 无法将十六进制字符串解析回 integer

[英]Why Integer.valueOf cannot parse the hex string back to integer

Why did the following code not work为什么下面的代码不起作用

System.out.println(Integer.valueOf(Integer.toOctalString(-1), 8));
System.out.println(Integer.valueOf(Integer.toBinaryString(-1), 2));
System.out.println(Integer.valueOf(Integer.toHexString(-1), 16));

If you read the documentation , ie the javadoc of Integer.toOctalString(int i) , you will find:如果您阅读文档,即Integer.toOctalString(int i)的 javadoc,您会发现:

Returns a string representation of the integer argument as an unsigned integer in base 8.将 integer 参数的字符串表示形式返回为基数为 8 的无符号integer。

[...] [...]

The value of the argument can be recovered from the returned string s by calling Integer.parseUnsignedInt(s, 8) .可以通过调用Integer.parseUnsignedInt(s, 8)从返回的字符串s中恢复参数的值。

Javadoc of Integer.toBinaryString(int i) and Integer.toHexString(int i) says exactly the same thing, except the base is of course different ( 2 and 16 , respectively). Integer.toBinaryString(int i)Integer.toHexString(int i)的 Javadoc 说的完全一样,除了基数当然不同(分别为216 )。

System.out.println(Integer.parseUnsignedInt(Integer.toOctalString(-1), 8));
System.out.println(Integer.parseUnsignedInt(Integer.toBinaryString(-1), 2));
System.out.println(Integer.parseUnsignedInt(Integer.toHexString(-1), 16));

Output Output

-1
-1
-1

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

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