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

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?

2

12 Answers

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

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

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

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

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 

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

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

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; 

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

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

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 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like