Will J
Will J

Reputation: 23

Decimal to binary assignment in Java

Hi I have an assignment where I have to convert a variable 'binary' (which is a random binary (11001 for example)) and print it.

It's hard because there is no potency feature built in Java

Example: 1010 = 1*2^3 + 0*2^2 + 1*2^1 + 0*2^0 = 8 + 0 + 2 + 0 = 10

What's wrong with my code?

int a = 1;
int b = 0;
for (int i=binary.length()-1;i>0;i--){
    if (binary.charAt(binary.length()-1) == '1'){
        b += 1;
    if (binary.charAt(i) == '1'){
        for (int j=binary.length()-1;j>0;i--){
            a = a*2;
        }
    }
    }
}
System.out.println(a+b);

Currently it only prints "1"

Upvotes: 1

Views: 61

Answers (3)

forpas
forpas

Reputation: 164099

Your code tries to calculate each power of 2 with a for loop, which is ok although there are simpler ways in Java.
By your standards you could do this:

String binary = "111011";
int sum = 0;
for (int i = binary.length() - 1; i >= 0 ; i--){
    if (binary.charAt(i) == '1'){
        int a = 1;
        for (int j = 1; j < binary.length() - i; j++) {
            a *= 2;
        }
        sum += a;
    }
}
System.out.println(sum);

It prints 59.
Something that was wrong in your code was the condition i > 0,
it should be i >= 0 otherwise you lose the 1st char of the string.

Upvotes: 0

Eran
Eran

Reputation: 393846

You are iterating over the characters from the least significant digit to the most significant (though you are skipping the most significant digit), but for some reason you always check if the last character is '1' instead of checking the current character.

Using similar code to your loop, I suggest:

int result = 0;
int a = 1;
for (int i = binary.length() - 1; i >= 0; i--) {
    if (binary.charAt(i) == '1') {
        result += a; // this adds 2^k to the result for each '1' digit, since a is initialized
                     // to 2^0 and is multiplied by 2 in each iteration
    }
    a *= 2;
}

For example, if binary is initialized to "10010011", result is 147.

Upvotes: 1

Schidu Luca
Schidu Luca

Reputation: 3947

Actually there is a static method in Integer , parseInt(String s, int radix) which can solve your problem:

String binary = "11001010110";
int result = Integer.parseInt(binary, 2);

Upvotes: 2

Related Questions