1

I have the following code for a recursive function to convert binary to int:

public static int binaryToInt( String b ) {

    if(b.length() < 2) {
        return 0;
    }

    return b.charAt(0) * (int) Math.pow(2, b.length()) + binaryToInt(b.substring(1));

}

I am not getting the correct values for example: "101" I get 584. I thought my logic is correct but can someone please point out where i am going wrong?

Chris
  • 375
  • 2
  • 15
  • 1
    Possible duplicate of [How to convert a Binary String to a base 10 integer in Java](https://stackoverflow.com/questions/10178980/how-to-convert-a-binary-string-to-a-base-10-integer-in-java) – Kaustubh Khare Mar 20 '18 at 05:46

3 Answers3

3

There are quite a few problems

  1. b.charAt(0) * ... - You are multiplying the ASCII value of the character and an int. Change it to b.charAt(0) - '0' to get the actual integer.

  2. Math.pow(2, b.length()) - It has to Math.pow(2, b.length() - 1). Working for a few samples with a pen and paper will explain this.

  3. The base condition is wrong. You need to return when there are no more characters left. So, it must be if(b.length() == 0)
user7
  • 14,505
  • 3
  • 35
  • 62
1

First: I changed your base criteria to allow all of the bits in calculation:

if(b.length() <= 0) {
    return 0;
 }

Second: b.charAt(0) return the ASCII value not the integer, so make it integer by using: (b.charAt(0) - '0')

Third: The power of each position will be length-1, so changed as following:

Math.pow(2, b.length()-1)

Final solution:

Please check the final solution:

public static int binaryToInt( String b ) {

    if(b.length() <= 0) {
        return 0;
    }

    return (b.charAt(0) - '0') * (int) Math.pow(2, b.length()-1) + binaryToInt(b.substring(1));

}
I. Ahmed
  • 2,287
  • 1
  • 9
  • 28
0

The code you have has the following errors:

  1. b.charAt(0)- returns the ASCII value of the character that means result is calculated as ASCCI value (i.e if b.charAt(0) returns 1 then its corresponding ASCII value is 49).

  2. if (b.length() < 2)- You are not checking the value of string what if the value is 1 still it returns 0.

  3. the Math.pow(2, b.length()) to be modified as Math.pow(2, b.length()-1)

Here is the code:

public static int binaryToInt( String b ) {

    if(b.length() < 2) {
        if(b.charAt(0)=='1')
            return 1;
        return 0;
    }

    return Character.getNumericValue(b.charAt(0)) * (int) Math.pow(2, b.length()-1) + binaryToInt(b.substring(1));

}
Vikas Satpute
  • 172
  • 2
  • 17