How to convert a Binary String to a base 10 integer in Java

做~自己de王妃 提交于 2019-11-26 08:59:50

问题


I have an array of Strings that represent Binary numbers (without leading zeroes) that I want to convert to their corresponding base 10 numbers. Consider:

binary 1011 becomes integer 11
binary 1001 becomes integer 9
binary   11 becomes integer 3   etc. 

What\'s the best way to proceed? I\'ve been exploring java.lang.number.* without finding a direct conversion method. Integer.parseInt(b) yields an integer EQUAL to the String...e.g., 1001 becomes 1,001 instead of 9...and does not seem to include a parameter for an output base. toBinaryString does the conversion the wrong direction. I suspect I\'ll need to do a multistep conversion, but can\'t seem to find the right combination of methods or subclasses. I\'m also not sure the extent to which leading zeros or lack thereof will be an issue. Anyone have any good directions to point me?


回答1:


You need to specify the radix. There's an overload of Integer#parseInt() which allows you to.

int foo = Integer.parseInt("1001", 2);



回答2:


This might work:

public int binaryToInteger(String binary) {
    char[] numbers = binary.toCharArray();
    int result = 0;
    for(int i=numbers.length - 1; i>=0; i--)
        if(numbers[i]=='1')
            result += Math.pow(2, (numbers.length-i - 1));
    return result;
}



回答3:


int foo = Integer.parseInt("1001", 2);

works just fine if you are dealing with positive numbers but if you need to deal with signed numbers you may need to sign extend your string then convert to an Int

public class bit_fun {
    public static void main(String[] args) {
        int x= (int)Long.parseLong("FFFFFFFF", 16);
        System.out.println("x =" +x);       

        System.out.println(signExtend("1"));
        x= (int)Long.parseLong(signExtend("1"), 2);
        System.out.println("x =" +x);

        System.out.println(signExtend("0"));
        x= (int)Long.parseLong(signExtend("0"), 2);
        System.out.println("x =" +x);

        System.out.println(signExtend("1000"));
        x= (int)Long.parseLong(signExtend("1000"), 2);
        System.out.println("x =" +x);

        System.out.println(signExtend("01000"));
        x= (int)Long.parseLong(signExtend("01000"), 2);
        System.out.println("x =" +x);
    }

    private static String signExtend(String str){
        //TODO add bounds checking
        int n=32-str.length();
        char[] sign_ext = new char[n];
        Arrays.fill(sign_ext, str.charAt(0));

        return new String(sign_ext)+str;
    }
}

output:
x =-1
11111111111111111111111111111111
x =-1
00000000000000000000000000000000
x =0
11111111111111111111111111111000
x =-8
00000000000000000000000000001000
x =8 

I hope that helps!




回答4:


static int binaryToInt (String binary){
    char []cA = binary.toCharArray();
    int result = 0;
    for (int i = cA.length-1;i>=0;i--){
        //111 , length = 3, i = 2, 2^(3-3) + 2^(3-2)
        //                    0           1  
        if(cA[i]=='1') result+=Math.pow(2, cA.length-i-1);
    }
    return result;
}



回答5:


public Integer binaryToInteger(String binary){
    char[] numbers = binary.toCharArray();
    Integer result = 0;
    int count = 0;
    for(int i=numbers.length-1;i>=0;i--){
         if(numbers[i]=='1')result+=(int)Math.pow(2, count);
         count++;
    }
    return result;
}

I guess I'm even more bored! Modified Hassan's answer to function correctly.




回答6:


For me I got NumberFormatException when trying to deal with the negative numbers. I used the following for the negative and positive numbers.

System.out.println(Integer.parseUnsignedInt("11111111111111111111111111110111", 2));      

Output : -9



回答7:


Fixed version of java's Integer.parseInt(text) to work with negative numbers:

public static int parseInt(String binary) {
    if (binary.length() < Integer.SIZE) return Integer.parseInt(binary, 2);

    int result = 0;
    byte[] bytes = binary.getBytes();

    for (int i = 0; i < bytes.length; i++) {
        if (bytes[i] == 49) {
            result = result | (1 << (bytes.length - 1 - i));
        }
    }

    return result;
}



回答8:


If you're worried about performance, Integer.parseInt() and Math.pow() are too expensive. You can use bit manipulation to do the same thing twice as fast (based on my experience):

final int num = 87;
String biStr = Integer.toBinaryString(num);

System.out.println(" Input Number: " + num + " toBinary "+ biStr);
int dec = binaryStringToDecimal(biStr);
System.out.println("Output Number: " + dec + " toBinary "+Integer.toBinaryString(dec));

Where

int binaryStringToDecimal(String biString){
  int n = biString.length();      
  int decimal = 0;
  for (int d = 0; d < n; d++){
    // append a bit=0 (i.e. shift left) 
    decimal = decimal << 1;

    // if biStr[d] is 1, flip last added bit=0 to 1 
    if (biString.charAt(d) == '1'){
      decimal = decimal | 1; // e.g. dec = 110 | (00)1 = 111
    }
  }
  return decimal;
}

Output:

 Input Number: 87 toBinary 1010111
Output Number: 87 toBinary 1010111



回答9:


I love loops! Yay!

String myString = "1001001"; //73

While loop with accumulator, left to right (l doesn't change):

int n = 0,
    j = -1,
    l = myString.length();
while (++j < l) n = (n << 1) + (myString.charAt(j) == '0' ? 0 : 1);
return n;

Right to left with 2 loop vars, inspired by Convert boolean to int in Java (absolutely horrible):

int n = 0,
    j = myString.length,
    i = 1;
while (j-- != 0) n -= (i = i << 1) * new Boolean(myString.charAt(j) == '0').compareTo(true);
return n >> 1;

A somewhat more reasonable implementation:

int n = 0,
    j = myString.length(),
    i = 1;
while (j-- != 0) n += (i = i << 1) * (myString.charAt(j) == '0' ? 0 : 1);
return n >> 1;

A readable version :p

int n = 0;
for (int j = 0; j < myString.length(); j++) {
    n *= 2;
    n += myString.charAt(j) == '0' ? 0 : 1;
}
return n;


来源:https://stackoverflow.com/questions/10178980/how-to-convert-a-binary-string-to-a-base-10-integer-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!