ngfusion
ngfusion

Reputation: 1

Convert from decimal to binary Java error

I'm writing a simple Java program to convert from decimal to binary.

public static int toBinary(int n) {
    int result = 0;

    while (n >= 1) {
        int power = 0;

        while ((int) Math.pow(2, power) <= n) {
            power++;
        }

        result += (int) Math.pow(10, power - 1);
        n = n - (int) Math.pow(2, power - 1);
    }

    return result;
}

The program works for n up until 1023, but fails after that and I'm not sure where I did wrong. Can someone help?

Upvotes: 0

Views: 66

Answers (1)

Harshal Parekh
Harshal Parekh

Reputation: 6017

Your code has a problem of Integer Overflow.

Binary of 1024 is 10,000,000,000 and the max value an int can hold is 2,147,483,647.

Use an int array to store the number:

public static void convertBinary(int num) {
    int[] binary = new int[40];
    int index = 0;
    while (num > 0) {
        binary[index++] = num % 2;
        num /= 2;
    }
    for (int i = index - 1; i >= 0; i--){
        System.out.print(binary[i]);
    }
}

You can also use the in-built method.

System.out.println(Integer.toBinaryString(1024));

You can also use StringBuilder to store the result:

public static void convertBinary(int num){
    StringBuilder binary = new StringBuilder();
    while (num > 0){
        binary.append(num % 2);
        num = num / 2;
    }
    System.out.println(binary.reverse());
}

Do not use String (immutable) in a loop, always use a StringBuilder (mutable).

Upvotes: 1

Related Questions