java:将二进制字符串转换为int

2022-01-09 00:00:00 binary casting java

我正在尝试将几个二进制字符串转换回 int.但是它不会转换我所有的二进制字符串,给我留下一个 java.lang.NumberFormatException 异常.这是我的带有 3 个二进制字符串的测试代码:

I'm trying to convert a couple of binary strings back to int. However it doesn't convert all my binary strings, leaving me a java.lang.NumberFormatException exception. Here is my test code with 3 binary string:

public class Bin {

    public static void main(String argvs[]) {
            String binaryString ;
            binaryString = Integer.toBinaryString(~0);
            //binaryString = Integer.toBinaryString(~1);
            //binaryString = "1010" ;
            int base = 2;
            int decimal = Integer.parseInt(binaryString, base);
            System.out.println("INPUT=" + binaryString + " decimal=" + decimal) ;
    }
}

如果我转换1010"效果很好,但是当我尝试转换另外两个之一时,我得到了异常.有人可以向我解释这是为什么吗?

If I convert the "1010" it works great, but when I try to convert one of the other two I get the exception. Can someone explain to me why this is ?

干杯

推荐答案

来自 http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#toBinaryString(int) :toBinaryString() 方法将其输入转换为无符号整数值是参数加上 232 如果参数为负数"的二进制表示.

From http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#toBinaryString(int) : the toBinaryString() method converts its input into the binary representation of the "unsigned integer value is the argument plus 232 if the argument is negative".

来自 http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#parseInt(java.lang.String,%20int) :parseInt() 方法抛出 NumberFormatException 如果字符串表示的值不是 int 类型的值".

From http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#parseInt(java.lang.String,%20int) : the parseInt() method throws NumberFormatException if "The value represented by the string is not a value of type int".

注意~0~1都是负数(分别为-1和-2),所以会转换成232的二进制表示-1 和 232-2 分别不能用 int 类型的值表示,所以导致 NumberFormatException 你所看到的.

Note that both ~0 and ~1 are negative (-1 and -2 respectively), so will be converted to the binary representations of 232-1 and 232-2 respectively, neither of which can be represented in a value of type int, so causing the NumberFormatException that you are seeing.

相关文章