Every number is a row of on/off switches. Bit tricks flip those switches directly.
Inside the computer a number is stored in binary: a row of switches, each either 0 (off) or 1 (on). Each switch has a place value: from the right they are 1, 2, 4, 8, 16, 32, 64, 128. Add up the values of the switches that are on. For example 00001100 is 8 + 4 = 12. This page uses 8 switches (Go’s uint8, numbers 0 to 255).
&): a column is 1 only if both numbers have 1 there. Great for checking or keeping bits.|): 1 if either has 1. Great for turning bits on.^): 1 if the bits are different. Doing it twice with the same value undoes it, so equal numbers cancel to 0.<< / >>): slide all switches left or right. Left by 1 doubles the number; right by 1 halves it.& with &&. & works on bits of numbers; && works on true/false values.& binds tighter than ==, so a & b == 0 means (a & b) == 0. In C and some other languages it is the other way round, so add parentheses when in doubt.uint8 cannot hold 1 << 8.int keeps the sign bit; this page uses unsigned numbers to keep things simple.O(1)). Counting bits with n & (n-1) loops once per 1 bit, not once per bit position. The single-number trick scans the list once and needs no extra memory.