Groovy Bitwise Operations Monday, June 3, 2013

long bits = 1L

for (pos in 0..63){
    print pos + ": \t"
    // To set a bit
    bits |= (1L << pos)

    // To unset a bit
    // In this case, unset the one behind the one we just set
    bits &= ~(1L << pos - 1)
    println Long.toBinaryString(bits)
}

Output:

0: 1
1: 10
2: 100
3: 1000
4: 10000
5: 100000
6: 1000000
7: 10000000
8: 100000000
9: 1000000000
10: 10000000000
11: 100000000000
12: 1000000000000
13: 10000000000000
14: 100000000000000
15: 1000000000000000
16: 10000000000000000
17: 100000000000000000
18: 1000000000000000000
19: 10000000000000000000
20: 100000000000000000000
21: 1000000000000000000000
22: 10000000000000000000000
23: 100000000000000000000000
24: 1000000000000000000000000
25: 10000000000000000000000000
26: 100000000000000000000000000
27: 1000000000000000000000000000
28: 10000000000000000000000000000
29: 100000000000000000000000000000
30: 1000000000000000000000000000000
31: 10000000000000000000000000000000
32: 100000000000000000000000000000000
33: 1000000000000000000000000000000000
34: 10000000000000000000000000000000000
35: 100000000000000000000000000000000000
36: 1000000000000000000000000000000000000
37: 10000000000000000000000000000000000000
38: 100000000000000000000000000000000000000
39: 1000000000000000000000000000000000000000
40: 10000000000000000000000000000000000000000
41: 100000000000000000000000000000000000000000
42: 1000000000000000000000000000000000000000000
43: 10000000000000000000000000000000000000000000
44: 100000000000000000000000000000000000000000000
45: 1000000000000000000000000000000000000000000000
46: 10000000000000000000000000000000000000000000000
47: 100000000000000000000000000000000000000000000000
48: 1000000000000000000000000000000000000000000000000
49: 10000000000000000000000000000000000000000000000000
50: 100000000000000000000000000000000000000000000000000
51: 1000000000000000000000000000000000000000000000000000
52: 10000000000000000000000000000000000000000000000000000
53: 100000000000000000000000000000000000000000000000000000
54: 1000000000000000000000000000000000000000000000000000000
55: 10000000000000000000000000000000000000000000000000000000
56: 100000000000000000000000000000000000000000000000000000000
57: 1000000000000000000000000000000000000000000000000000000000
58: 10000000000000000000000000000000000000000000000000000000000
59: 100000000000000000000000000000000000000000000000000000000000
60: 1000000000000000000000000000000000000000000000000000000000000
61: 10000000000000000000000000000000000000000000000000000000000000
62: 100000000000000000000000000000000000000000000000000000000000000
63: 1000000000000000000000000000000000000000000000000000000000000000