java-convert decimal to any binary bit

馋奶兔 提交于 2019-12-14 03:36:28

问题


I'm making a project of converting decimal number into binary. But I have a problem that how can I convert any entered number into binary (I'm using array), here is my code:

    public void Decimal2Binary(int a)
{
    int result []=new int[8];
    for (int i = 7;i >=0; i--,a/=2) {
        result[i]=a%2;
}

I do not need it for just only 8-bit binary result, yet, I need it for any size.


回答1:


use this function Integer.toBinaryString(int)... and why do you want it to be in a array ? can't it be an array list or big decimal.




回答2:


You don't actually specify the output, but here goes.

assuming unsigned (as it looks like you have).

StringBuilder result = new StringBuilder();
while(a > 0) {
    result.append(a % 2);
    a = a / 2; // This will round down automatically. ;)
}

If you need to handle negative numbers, I would do bitwise comparisons using the & operator - you could also use >> for the division, but I am leaving that optimisation for the compiler to keep the source more readable.

obviously you could change that to any form of append



来源:https://stackoverflow.com/questions/25666293/java-convert-decimal-to-any-binary-bit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!