Home > other >  Loop and return all bitwise values in Long
Loop and return all bitwise values in Long

Time:10-06

To set bits, you use the OR operator. You can then use the AND operator to see which bits have been set:

long values = 0;

// Set bits
values |= (1L << 10);
values |= (1L << 45);
values |= (1L << 56);

// Check if values are set
System.out.println(hasValue(values, 45)); // Returns true
System.out.println(hasValue(values, 55)); // Returns false

public static boolean hasValue(long data, int value)
{
    return (((data >> value) & 1L) > 0);
}

Is it possible to loop through values and return each of the values originally set with the OR operator? The result printing:

Found value: 10
Found value: 45
Found value: 56

CodePudding user response:

You could use your function inside of a loop from 0 to 64 to find everything like so:

for (int i = 0; i < 64; i  ) {
    if (hasValue(values, i))
        System.out.println(“Found value: “   i);
}

But I think there’s a better way. It’s destructive to the variable so if you want to save it for later do it before the loop but here it is:

for (int i = 0; i < 64 && values != 0; i  ) {
    if (values % 2 == 0)
        System.out.println(“Found value: “   i);
    values = values >> 1;
}

The big advantage is to shift one bit at a time and not i bits every time needed.

CodePudding user response:

I hope I understand question correctly. You just need to shift values by 1, and check youngest bit by AND 1 like that:

class Main {  
    public static void main(String args[]) { 
        long v = 0;
        v |= (1L << 10);
        v |= (1L << 45);
        v |= (1L << 56);
        int i = 0;
        while(v != 0) {
            if((v & 1L) == 1) {
                 System.out.println("Found value: "   i);
            }
            v = v >>> 1;
            i  ;
        }
    } 
}

CodePudding user response:

Java long has 64 bits.

So you could use 8 bits and store a maximum of 8 integers whose value is between 0 and 255 (unsigned).

You will need to use shift and then store.

So first unsigned byte will be 0-7 bits, second would be 8-15, third being 16-23 and so on.

But not otherwise.

  • Related