Search code examples
javabit-manipulationbitwise-operators

Loop and return all bitwise values in Long


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 << 5600);

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

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: 5600

Edit: Altered example to include larger numbers.


Solution

  • 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++;
            }
        } 
    }