0

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?

3
  • Could you perhaps elaborate on „fails after that“. This is not very expressive... Commented May 20, 2020 at 22:06
  • Ints are already in binary. What you want is the binary representation of a decimal number. So just use Integer.toBinaryString(). If you grow your own, store the result in a String, not an int. Here is one example of how to do it. Commented May 20, 2020 at 22:10
  • May I suggest using a Bitset to store the result of your conversion? Commented May 20, 2020 at 22:35

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

1 Comment

If you're going to tell the OP how to do it then don't use an array. Use a StringBuilder or just a String.

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.