Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which bit is on for an integer in Java

I have written this code to check which bits are on of an Integer (if represented in binary) in Java:

public static List<String> list(int val)
{
    List<String> dummyList = new ArrayList<String>();

    int bit = 1;
    int x;

    for(int i=0; i<32; i++)
    {
        x = bit;
        if((x&val)!=0)
            dummyList.add(String.valueOf(i+1));
        bit = bit << 1;
    }

    return dummyList;
}

The above written code works fine. But it has a loop which runs 32 times (In Java integer is 32 bit long). I want to minimize this complexity. Please share the better solution. Thanks in advance.

like image 463
Comet Avatar asked Nov 14 '22 05:11

Comet


1 Answers

You could use a bit mask to try to reduce the times through the loop. You add a few operations but potentially do half the looping:

public static List<String> list(int val) {
    List<String> dummyList = new ArrayList<String>();
    int loop = 32;

    // Mask the 16 MSB if all are zero only loop on the 16 LSB
    if((val & 0xFFFF0000) == 0){
        loop = 16;
    }

    int bit = 1;
    int x;

    for (int i = 0; i < loop; i++) {
        x = bit;
        if ((x & val) != 0) {
            dummyList.add(String.valueOf(i + 1));
        }
        bit <<= 1;
    }

    return dummyList;
}

This potentially would increase time depending on the data coming in.

You can also reduce looping in half by doing two bits at a time:

public static List<String> list(int val) {
    List<String> dummyList = new ArrayList<String>();

    int bit = 3;
    int x;

    for (int i = 0; i < 32; i += 2) {
        x = (bit & val);
        switch (x) {
            case 1:
                dummyList.add(String.valueOf(i + 1));
                break;
            case 2:
                dummyList.add(String.valueOf(i+2));
                break;
            case 3:
                dummyList.add(String.valueOf(i+1));
                dummyList.add(String.valueOf(i+2));
                break;
            default:
        }
        val >>= 2;
    }

    return dummyList;
}
like image 154
kfaerber Avatar answered Nov 16 '22 04:11

kfaerber