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

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

问题描述

我正在尝试将几个二进制字符串转换回 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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Android schema validation(Android 架构验证)
Required Multiple beans of same type in Spring(Spring中需要多个相同类型的bean)
How to deal with JAXB ComplexType with MixedContent data?(如何处理带有 MixedContent 数据的 JAXB ComplexType?)
Validate an XML File Against Multiple Schema Definitions(针对多个模式定义验证 XML 文件)
JAXB - Property quot;Valuequot; is already defined. Use lt;jaxb:propertygt; to resolve this conflict(JAXB - 属性“值;已经定义了.使用 lt;jaxb:propertygt;解决这个冲突)
XML instance generation from XML schema (xsd)(从 XML 模式 (xsd) 生成 XML 实例)