java-convert decimal to any binary bit

2019-09-22 03:23发布

问题:

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