java如何把二进制字符串转成整数

public class Test {
public static void main(String[] args) {
String str = "010111010110";
int[] a = toInt(str);
for(int i = 0;i<3;i++){
System.out.println(a[i]);
}
}
public static int[] toInt(String str){
if(str.length()!=12){
System.out.println("传入参数有误");
return null;
}else{
int[] targets = new int[3];
String tem1 = str.substring(0, 4);
String tem2 = str.substring(4, 8);
String tem3 = str.substring(8, 12);
targets[0] = Integer.parseInt(tem1);
targets[1] = Integer.parseInt(tem2);
targets[2] = Integer.parseInt(tem3);
return targets;
}
}
这里我把str平均分成3份,用Integer.parseInt()函数进行转换,可是他是按有符号类型转换的,得到的结果也不是整数,结果如下
101
1101
110
想要变成这样的形式,该怎么做
5
13
6

    java将二进制装换成整数,可以使用Integer类的方法,来进行转换,如下:

Integer.parseInt("80000000",2);

 Integer属于int基本类型的包装类,可以实现各个类型的互相转换,还可以输出成string类型,只需要使用toString()方法。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-09-11
public class Zhuang {

public static void main(String[] args) {
String str = "110";
int s=Integer.parseInt(str,2);//使用第二个参数指定的基数,将字符串参数解析为有符号的整数!
System.out.println(s);
}
}本回答被提问者采纳
第2个回答  2015-06-04
第一种方法:使用:Integer.valueOf("0101",2) ,如下:
int[] targets = new int[3];
String tem1 = str.substring(0, 4);
String tem2 = str.substring(4, 8);
String tem3 = str.substring(8, 12);
targets[0] = Integer.valueOf(tem1,2);
targets[1] = Integer.valueOf(tem2,2);
targets[2] = Integer.valueOf(tem3,2);
return targets;
第二种方法:使用,BigInteger bi = new BigInteger(tem1 , 2);//转换为BigInteger类型

如,targets[0] = Integer.valueOf(bi.toString(10));//转换为10进制结果
targets[1],targets[2],类似赋值就可以了。
第3个回答  2015-06-04

懒得写了,自己看吧,代码给你

public static void main(String args[]) {
String s = "101011110001";
int x = 0;
for (char c : s.toCharArray()) {
x = x * 2 + (c == '1' ? 1 : 0);
}
System.out.println(x);
}

第4个回答  2015-06-04
String str="1101";
System.out.println( Integer.parseInt(str, 2) );

13
相似回答