0

I can not seem to get my method to convert the binary number to a decimal correctly. I believe i am really close and in fact i want to use a string to hold the binary number to hold it and then re-write my method to just use a .length to get the size but i do not know how to actually do that. Could someone help me figure out how i'd rewrite the code using a string to hold the binary value and then obtain the decimal value using only recursion and no loops?

This is my full code right now and i won't get get rid of asking for the size of the binary and use a string to figure it out myself. Please help :)

package hw_1;
import java.util.Scanner;


public class Hw_1 {

    public static void main(String[] args) {

        int input;
        int size;
        Scanner scan = new Scanner(System.in);

        System.out.print("Enter decimal integer: ");
        input = scan.nextInt();
        convert(input);
        System.out.println();
        System.out.print("Enter binary integer and size : ");
        input = scan.nextInt();
        size = scan.nextInt();
        System.out.println(binaryToDecimal(input, size));

    }

    public static void convert(int num) {
        if (num > 0) {
            convert(num / 2);
            System.out.print(num % 2 + " ");
        }
    }

    public static int binaryToDecimal(int binary, int size) {
        if (binary == 0) {
            return 0;
        }
        return binary % 10
                * (int) Math.pow(2, size) + binaryToDecimal((int) binary / 10, size - 1);

    }
}
5
  • 3
    I assume this must be a homework assignment, since there is a method built into java.lang.Integer that will do this for you. I/we could tell you the answer, but then what would you be learning? Commented Jan 20, 2015 at 18:34
  • I've explained that i know what i need to do- i just don't know the syntax or setup to do so. I'm asking for help Commented Jan 20, 2015 at 18:40
  • By refusing to use a string you've made things somewhat more difficult. In general by using binary%10 and getting the ones digit and then multiplying that 2^size you are reversing the number. Commented Jan 20, 2015 at 18:46
  • how do i implement the string though? i know i need to do that but i can't figure out how Commented Jan 20, 2015 at 18:47
  • Make input a String and use scan.next() Consider "1010", end recursion when the string is empty. input.charAt(0) is the first character (a one in this case). input.length() is the number of characters (your current size) and input.substring(1) will return "010" or everything after the character at location 0. Commented Jan 20, 2015 at 18:49

5 Answers 5

2

Here is an improved version

package hw_1;
import java.util.Scanner;

public class Hw_1 {
  public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    System.out.print("Enter decimal integer : ");
    int input = scan.nextInt();
    convert(input);
    System.out.println();
    System.out.print("Enter binary integer : ");
    String binInput = scan.next();
    System.out.println(binaryToDecimal(binInput));
  }

  public static void convert(int num) {
    if (num>0) {
      convert(num/2);
      System.out.print(num%2 + " ");
    }
  }

  public static int binaryToDecimal(String binInput){  
    int len = binInput.length();
    if (len == 0) return 0;
    String now = binInput.substring(0,1);
    String later = binInput.substring(1);
    return Integer.parseInt(now) * (int)Math.pow(2, len-1) + binaryToDecimal(later);     
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

This helped a lot! The last part i had to change a tad but you helped me get the idea! I mixed your second method with the comment below this one- thanks man!
Now when you done with your assignment, it should be nice to know that there are build-in solution for such conversion. Particularly Integer.parseInt(binInput, 2) will do the same as your binToDecimal metod.
1

Don't parse binary in reverse order.
Here by calling binaryToDecimal(int) it will return decimal number.

public static int binaryToDecimal(int binary) {
    return binaryToDecimal(binary, 0);
}

public static int binaryToDecimal(int binary, int k) {
    if (binary == 0) {
        return 0;
    }
    return (int) (binary % 10 * Math.pow(2, k) + binaryToDecimal(binary / 10, k + 1));
}

If you are coding just to convert numbers (not for practice). Then better approach would be to use Integer.parseInt(String, 2). Here you will have to pass binary number in the form of String.

Comments

1

If you are looking to do this using a String to hold the binary representation, you could use the following:

public static int binaryToDecimal(String binaryString) {

    int size = binaryString.length();
    if (size == 1) {
        return Integer.parseInt(binaryString);
    } else {
        return binaryToDecimal(binaryString.substring(1, size)) + Integer.parseInt(binaryString.substring(0, 1)) * (int) Math.pow(2, size - 1);
    }

}

How this works, is with the following logic. If, the number you send it is just 1 character long, or you get to the end of your recursive work, you will return just that number. So for example, 1 in binary is 1 in decimal, so it would return 1. That is what

if (size == 1) {
        return Integer.parseInt(binaryString);
}

Does. The second (and more important part) can be broken up into 2 sections. binaryString.substring(1, size) and Integer.parseInt(binaryString.substring(0, 1)) * (int) Math.pow(2, size - 1). The call made in the return statement to

binaryString.substring(1, size)

Is made to pass all but the first number of the binary number back into the function for calculation. So for example, if you had 11001, on the first loop it would chop the first 1 off and call the function again with 1001. The second part, is adding to the total value whatever the value is of the position number at the head of the binary representation.

Integer.parseInt(binaryString.substring(0, 1))

Gets the first number in the current string, and

* (int) Math.pow(2, size - 1)

is saying Multiple that by 2 to the power of x, where x is the position that the number is in. So again with our example of 11001, the first number 1 is in position 4 in the binary representation, so it is adding 1 * 2^4 to the running total.

If you need a method to test this, I verified it working with a simple main method:

public static void main(String args[]) {
    String binValue = "11001";
    System.out.println(binaryToDecimal(binValue));
}

Hopefully this makes sense to you. Feel free to ask questions if you need more help.

Comments

0

Here is the clean and concise recursive algorithm; however, you'll need to keep track of some global variable for power, and I have defined it as a static member.

static int pow = 0;

public static int binaryToDecimal(int binary) {
    if (binary <= 1) {
        int tmp = pow;
        pow = 0;
        return binary * (int) Math.pow(2, tmp);
    } else {
        return ((binary % 10) * (int) Math.pow(2, pow++)) + binaryToDecimal(binary / 10);
    }
}

Note: the reason, why I introduce pow, is that static field needs to be reset.

Comments

0

Just did the necessary changes in your code. In this way, you would not require the size input from the user. And,both the conversions of decimal to binary and binary to decimal would be succesfully done.

package hw_1;
import java.util.Scanner;
public class Hw_1 {
public static void main(String[] args) {

    int input;
    int size;
    Scanner scan = new Scanner(System.in);

    System.out.print("Enter decimal integer: ");
    input = scan.nextInt();
    convert(input);
    System.out.println();
    System.out.print("Enter binary integer : ");
    input = scan.nextInt();
    System.out.println(binaryToDecimal(input));

}

public static void convert(int num) {
    if (num > 0) {
        convert(num / 2);
        System.out.print(num % 2 + " ");
    }
    return -1;
}
public static int binaryToDecimal(int binary) {
    if(binary==0)
    {
        return 0;
    }
    else
    {
        String n=Integer.toString(binary);
        int size=(n.length())-1;
        int k=(binary%10)*(int)(Math.pow(2,size));
        return k + binaryToDecimal(((int)binary/10));
    }

}

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.