java 十进制到二进制的转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4158428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 05:06:13  来源:igfitidea点击:

Decimal-to-binary conversion

javaarraysbinarydecimalbase-conversion

提问by Upvote

I want to convert decimal numbers to binary numbers. I want to store them in an array. First I need to create an array that has a certain length so that I can store the binary numbers. After that I perform the conversion, here is how I do it:

我想将十进制数转换为二进制数。我想将它们存储在一个数组中。首先,我需要创建一个具有特定长度的数组,以便我可以存储二进制数。之后我执行转换,这是我的方法:

public class Aufg3 {
    public static void main(String[] args) {
        int[] test = decToBin(12, getBinArray(12));
        for(int i = 0; i < test.length; i++){
            System.out.println(test[i]);
        }
    }

    public static int[] getBinArray(int number){
        int res = number, length = 0;
        while(res != 0){        
            res /= 2;
                    length++;
        }
        return new int[length];
    }

    public static int[] decToBin(int number, int[] array){
        int res = number, k = array.length-1;
        while(res != 0){
            if(res%2 == 0){
                array[k] = 0;
            }else{
                array[k] = 1;
            }
            k--;
            res /= 2;
        }
        return array;
    }
}

Is there anything to improve? It should print 1100 for input of 12.

有什么可以改进的吗?对于 12 的输入,它应该打印 1100。

采纳答案by Grodriguez

I assume you want to write your own code -- otherwise this is straightforward to do using methods from the standard Java library.

我假设您想编写自己的代码——否则使用标准 Java 库中的方法很容易做到这一点。

Some quick comments:

一些快速评论:

  • You can get rid of the restemp vars. Work directly on number(remember that Java passes parameters by value).
  • Shift is more efficient than division (number >>>= 1instead of number /= 2), although the compiler should be able to optimize this anyway
  • You can avoid the modulus in decToBinif you just do array[k] = number & 1;
  • While you are at it, why not call getBinArrayfrom decToBindirectly? Then you can call decToBinwith only one arg -- the value to convert.
  • 您可以摆脱res临时变量。直接处理number(记住 Java 按值传递参数)。
  • Shift 比除法(number >>>= 1而不是number /= 2)更有效,尽管编译器无论如何都应该能够优化它
  • decToBin如果你只是这样做,你可以避免模数array[k] = number & 1;
  • 当你在它,为什么不叫getBinArraydecToBin直接?然后你可以decToBin只用一个参数调用——要转换的值。

Here is a slightly optimized version of your code:

这是您的代码的稍微优化的版本:

public static int[] getBinArray(int number) {
    int length = 0;
    while (number != 0) {
        number >>>= 1;
        length++;
    }
    return new int[length];
}

public static int[] decToBin(int number) {
    int[] array = getBinArray(number);
    int k = array.length-1;
    while (number != 0)
    {
        array[k--] = number & 1;
        number >>>= 1;
    }
    return array;
}

回答by codaddict

Why not just use the toBinaryStringmethod of the Integer class:

为什么不直接使用Integer 类的toBinaryString方法:

System.out.println(Integer.toBinaryString(12))

回答by nojo

If this isn't homework, no need to do it yourself. The following code should work:

如果这不是家庭作业,则无需自己做。以下代码应该可以工作:

BigInteger bigInt = new BigInteger(number);
String asString = bigInt.toString(2);

There might be more efficient ways, but this is certainly very readable and maintainable.

可能有更有效的方法,但这肯定是非常可读和可维护的。

回答by Roland Illig

There are some small things that you can improve:

有一些小事情你可以改进:

  • You should define a "high-level" method that converts an intto an int[]. In the current code you have to mention the 12two times, which is bad.
  • You should use a do { ... } while (number != 0)loop. Otherwise the number 0will be represented by an empty array.
  • You should use x >>> 1instead of x / 2, since that handles negative numbers correctly.
  • If you want to check that your code is correct, write another method that converts back from binary to int. Then you can check that binToDec(decToBin(12, ...)) == 12.
  • The method getBinArrayshould not be public, since it is only a helper method. You can either replace the publicwith privateor just remove the public.
  • 您应该定义一个将 an 转换intint[]. 在当前的代码中,您必须提到12两次,这很糟糕。
  • 您应该使用do { ... } while (number != 0)循环。否则,数字0将由一个空数组表示。
  • 您应该使用x >>> 1而不是x / 2,因为它可以正确处理负数。
  • 如果您想检查您的代码是否正确,请编写另一种从二进制转换回int. 然后你可以检查一下binToDec(decToBin(12, ...)) == 12
  • 该方法getBinArray不应该是public,因为它只是一个辅助方法。您可以将 替换为public,也可以private仅删除public