How to convert a Binary String to a base 10 integer in Java
Asked Answered
Q

13

157

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?

Quake answered 16/4, 2012 at 17:45 Comment(2)
Look at Integer#parseInt(String s, int radix)Geography
possible duplicate of converting Binary Numbers in to decimal numbersAnstice
N
375

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

int foo = Integer.parseInt("1001", 2);
Nil answered 16/4, 2012 at 17:47 Comment(3)
Perfection. I completely missed the second line on the parseInt documentation that allows for the radix. Works like a dream.Quake
Does this work with leading zeros too? Just confirming, although I see no reason why not.Kafir
@NagabhushanBaddi example? Are you passing a two's complement representation?Nil
M
25

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;
}
Marilla answered 16/4, 2012 at 17:56 Comment(9)
I suppose it is kind of unnecessary. That's what happens when you have a little time between classes.Marilla
this one is helpful for me because I have to do a school project with conversions without using the ones java already hasJenine
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 onPendley
(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; }Pendley
This code snippet is not working. for loop and calculation of new result variable is not correct.Sweepstakes
i==0; that won't work why so many upvotes for a not working code?Liv
@Liv 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.Marilla
It's good for learning instead of having some high level function spur out some numbers.Wichern
This is really inefficient. Why the high number of upvotes I don't understand :(.Stubstad
A
15
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!

Aggri answered 15/4, 2014 at 15:58 Comment(1)
I needed -1 converted from binary to decimal, i did this. System.out.println((int)Long.parseLong("11111111111111111111111111111111",2));Anabolism
S
6
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;
}
Similitude answered 3/12, 2014 at 9:50 Comment(0)
O
4

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

Obsidian answered 1/7, 2021 at 10:55 Comment(0)
S
3
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.

Swisher answered 11/10, 2013 at 0:9 Comment(0)
A
3

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
Anabolism answered 19/8, 2019 at 16:22 Comment(0)
B
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;
Burier answered 20/11, 2015 at 5:31 Comment(0)
P
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;
}
Protectionist answered 16/6, 2016 at 20:3 Comment(0)
D
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;
}
Daphne answered 23/12, 2020 at 1:51 Comment(0)
B
0

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);
}
Bimanous answered 7/1, 2022 at 12:5 Comment(0)
V
0

For some bigger numbers including longs this method may be more helpful

public static long binCon(String s) {
    long num = 0;
    for (int i = 0; i < s.length(); i++) {
        char digit = s.charAt(i);
        if (digit == '1') 
            num = (num << 1) | 1; 
        else if (digit == '0') 
            num = num << 1;
    }
    return num;
}
Venettavenezia answered 13/4 at 1:10 Comment(0)
L
-1

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
Leeds answered 28/2, 2017 at 16:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.