java的:转换二进制字符串为int [英] java: convert binary string to int

查看:464
本文介绍了java的:转换二进制字符串为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一对夫妇二进制字符串的转换回int类型。然而,它并没有将我所有二进制字符串,留下了我的 java.lang.NumberFormatException 例外。
下面是我的测试code 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()方法转换成无符号整数值为参数加上2 32 如果参数为负的。

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".

从<一个href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#parseInt(java.lang.String,%20int)\" rel=\"nofollow\">http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#parseInt(java.lang.String,%20int) :在 parseInt函数()方法抛出 NumberFormatException异常如果的由字符串psented转口货值为$ P $是类型不是值 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分别),所以将被转换成的二进制重新presentations 2 32 -1和2 32 -2分别两者都不可以重新在一值psented $ p $键入 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.

这篇关于java的:转换二进制字符串为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆