Joseph101
Joseph101

Reputation: 23

Binary to decimal converter function gives wrong solution

Like the title says, I've made a small function that takes from the user string of ones and zeros and the output should be its decimal number but for some reason I get wrong answers, hope you'll help me find the problem.

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

    String string = args[0];

    int length = string.length();
    int power = length - 1;
    int decimal = 0;

    while(length > 0){

        if (string.charAt(length - 1) == '1'){
            decimal = decimal + (int)(Math.pow(2, length - 1));
        } else if (string.charAt(length - 1) == '0'){

        } else {
            System.out.println("Wrong string spelling...");
        }

        length--;
    }

    System.out.println(decimal);

}

}

Upvotes: 0

Views: 66

Answers (2)

AbtPst
AbtPst

Reputation: 8008

just reversed the string in the beginning and added the condition to decrement power.

public static void main(String[] args){

    String string = new StringBuilder(args[0]).reverse().toString();
    int length = string.length();
    int power = length - 1;
    int decimal = 0;

    while(length > 0){

        if (string.charAt(length - 1) == '1'){
            decimal = decimal + (int)(Math.pow(2, length - 1));
        } else if (string.charAt(length - 1) == '0'){

        } else {
            System.out.println("Wrong string spelling...");
        }

        power--;
        length--;
    }

    System.out.println(decimal);

}
}

Without reverse

String string = args[0];
            int length = string.length();
            int power = length - 1;
            int decimal = 0;
            int i=0;
            while(i<length){

                if (string.charAt(i) == '1'){
                    decimal = decimal + (int)(Math.pow(2, length - i-1));
                } 
                i++;

            }


            System.out.println(decimal);

Upvotes: 0

rgettman
rgettman

Reputation: 178253

You are applying the exponents in a backwards order. That is, on the first loop, you look at the last character, but apply the biggest exponent, length - 1, and the first character gets exponent 0.

Use power as the exponent instead of length - 1, and increment power at the end of the while loop.

    decimal = decimal + (int)(Math.pow(2, power));

and

    length--;
    power++;
}

Upvotes: 6

Related Questions