简体   繁体   English

Integer.valueOf 不适用于 Java 中 -1 的二进制表示

[英]Integer.valueOf not working for binary representation of -1 in Java

The following code attempts to output to obtain -1 from its 2's complement binary representation, but gives a NumberFormatException.以下代码尝试输出以从其 2 的补码二进制表示中获得 -1,但给出了 NumberFormatException。

System.out.println(Integer.parseInt(Integer.toBinaryString(-1), 2));  //Raises Exception

System.out.println(Integer.valueOf("11111111111111111111111111111111", 2));  //Raises Exception

Infact Integer.valueOf doesn't seem to work for any signed negative number's binary representation.事实上 Integer.valueOf 似乎不适用于任何有符号负数的二进制表示。 Why is the code outputting error?为什么代码输出错误?

valueOf doesn't know about 2's complement, so it thinks you are asking to covert an unsigned value in base 2 that is too large to fit in an int. valueOf不知道 2 的补码,因此它认为您要求转换基数为 2 的无符号值,该值太大而无法放入 int。 (Try removing one of the 1 's.) (尝试删除的一个1的。)

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

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