简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM