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

JavaStringBinaryRadix

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

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

Solution 2 - Java

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;
}

Solution 3 - Java

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!

Solution 4 - Java

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;
}

Solution 5 - Java

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.

Solution 6 - Java

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

Solution 7 - Java

Using bitshift is more elegant and faster than Math.pow. Simply bitshift the digits (0 or 1) into position with val <<= 1

// parse an unsigned binary string, valid up to 31 bits
static int binaryToBase10(String binaryString) {
    int val = 0;
    for (char c : binaryString.toCharArray()) {
        val <<= 1;
        val += c-'0';
    }
    return val;
}

Example use

int val = binaryToBase10("1011");
System.out.println(val);

prints 11

Solution 8 - Java

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 https://stackoverflow.com/q/3793650/2371861 (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;

Solution 9 - Java

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;
}

Solution 10 - Java

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;
}

Solution 11 - Java

You can also use this method to convert the binary to decimal integer if you are given with string.(Java Language)

static int binaryTodecimal(String s){
    int i= -1;
    char[] str = s.toCharArray();
    int dec_val= 0;
    
    for (int j=str.length-1; j>=0 ;j-- ){
        int k= Integer.valueOf(str[j]) - '0';
        i = i+1;
        dec_val += k*(Math.pow(2, i));
        
    }
    System.out.println(dec_val);
}

Solution 12 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiondwwilson66View Question on Stackoverflow
Solution 1 - JavaMatt BallView Answer on Stackoverflow
Solution 2 - Javauser377628View Answer on Stackoverflow
Solution 3 - JavatxcotraderView Answer on Stackoverflow
Solution 4 - JavaRudy DuranView Answer on Stackoverflow
Solution 5 - JavaModernIncantationsView Answer on Stackoverflow
Solution 6 - JavaZeusView Answer on Stackoverflow
Solution 7 - Javaimpossible-sudokuView Answer on Stackoverflow
Solution 8 - Javabjb568View Answer on Stackoverflow
Solution 9 - JavaskyrosbitView Answer on Stackoverflow
Solution 10 - JavaKooin-ShinView Answer on Stackoverflow
Solution 11 - JavaRicha-Bharti View Answer on Stackoverflow
Solution 12 - JavaanaskView Answer on Stackoverflow