简体   繁体   English

从十进制转换为二进制 Java 错误

[英]Convert from decimal to binary Java error

I'm writing a simple Java program to convert from decimal to binary.我正在编写一个简单的 Java 程序来将十进制转换为二进制。

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.该程序适用于 n 直到 1023,但在那之后失败了,我不确定我在哪里做错了。 Can someone help?有人可以帮忙吗?

Your code has a problem of Integer Overflow .您的代码存在Integer Overflow问题。

Binary of 1024 is 10,000,000,000 and the max value an int can hold is 2,147,483,647 . 1024的二进制是10,000,000,000并且int可以容纳的最大值是2,147,483,647

Use an int array to store the number:使用 int 数组存储数字:

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:您还可以使用StringBuilder来存储结果:

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).不要在循环中使用String (不可变),始终使用StringBuilder (可变)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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