简体   繁体   中英

java convert decimal to any binary bit

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.

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.

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

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