122

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?

Mike Samuel
  • 109,453
  • 27
  • 204
  • 234
dwwilson66
  • 6,086
  • 27
  • 66
  • 106
  • 4
    Look at [Integer#parseInt(String s, int radix)](http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#parseInt%28java.lang.String,%20int%29) – anubhava Apr 16 '12 at 17:49
  • possible duplicate of [converting Binary Numbers in to decimal numbers](http://stackoverflow.com/questions/2115346/converting-binary-numbers-in-to-decimal-numbers) – Mike Samuel Apr 16 '12 at 17:50

10 Answers10

302

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

int foo = Integer.parseInt("1001", 2);
Matt Ball
  • 332,322
  • 92
  • 617
  • 683
22

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;
}
Hassan
  • 5,278
  • 4
  • 37
  • 76
  • I suppose it is kind of unnecessary. That's what happens when you have a little time between classes. – Hassan Apr 16 '12 at 17:58
  • 6
    this one is helpful for me because I have to do a school project with conversions without using the ones java already has – bucksnort2 Oct 16 '13 at 13:46
  • Did anyone test this before? here number.length minus the index plus 1 is been multiply by 2, if i am not mistaken in bynary you start with 1 and multiply that value by 2 then grab the result and multiply that one by 2 that will be your 3 place and so on – Christopher Cabezudo Rodriguez Jun 23 '15 at 21:00
  • (COMMENT BOX IS NOT GOOD FOR SNIPPETS) Here the Code that i am using base in yours (I was lost and use yours as a template) public static int binaryToInteger(String binary) { char[] numbers = binary.ToCharArray(); int result = 0; int posValue = 1; for (int i = numbers.Length - 1; i >= 0 ; i--) { if (numbers[i] == '1') { result += posValue; } posValue *= 2; } return result; } – Christopher Cabezudo Rodriguez Jun 23 '15 at 21:01
  • 1
    This code snippet is not working. `for` loop and calculation of new `result` variable is not correct. – trylimits Aug 05 '15 at 11:19
  • `i==0;` that won't work why so many upvotes for a not working code? – fubo Sep 17 '15 at 15:10
  • @fubo Well, I hadn't tested it. I updated it to work now, but anyway, this solution is far from perfect and you should probably use Matt's solution instead. – Hassan Sep 17 '15 at 15:54
  • It's good for learning instead of having some high level function spur out some numbers. – Det Mar 02 '18 at 12:11
  • This is really inefficient. Why the high number of upvotes I don't understand :(. – Rohan Asokan Mar 01 '21 at 17:25
9
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!

txcotrader
  • 515
  • 1
  • 6
  • 18
  • 1
    I needed -1 converted from binary to decimal, i did this. System.out.println((int)Long.parseLong("11111111111111111111111111111111",2)); – Zeus Feb 28 '19 at 18:36
5
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;
}
Infinite Recursion
  • 6,315
  • 28
  • 36
  • 51
Rudy Duran
  • 51
  • 1
  • 3
2
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.

2

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
Zeus
  • 5,885
  • 5
  • 44
  • 79
0

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;
Community
  • 1
  • 1
bjb568
  • 9,826
  • 11
  • 45
  • 66
0

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;
}
skyrosbit
  • 66
  • 3
0

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
anask
  • 151
  • 1
  • 5
0

Now you want to do from binary string to Decimal but Afterword, You might be needed contrary method. It's down below.

public static String decimalToBinaryString(int value) {
    String str = "";
    while(value > 0) {
        if(value % 2 == 1) {
            str = "1"+str;
        } else {
            str = "0"+str;
        }
        value /= 2;
    }
    return str;
}
Kooin-Shin
  • 18
  • 3