A computer keeps every number in base two, in bits: 6 is 110 (4 + 2) and 3 is 011 (2 + 1). Bit operations compare the bits of two numbers at the same position: & (and) gives 1 if both are 1; | (or) if at least one is; ^ (exclusive or, XOR) if they differ.
a, b = 12, 10 # 1100, 1010a & b # 1000 -> 8a | b # 1110 -> 14a ^ b # 0110 -> 6a << 1 # 11000 -> 24a >> 2 # 11 -> 3
<< shifts the bits left; each shift multiplies the number by two. >> shifts right; each shift halves it and drops the rightmost bit. To find a result in your head, write the two numbers one under the other in binary.Two small pieces are useful everywhere. n & 1 is the number's rightmost bit (odd or even). n >> 1 drops that bit. Put the two in a loop and you read a number's bits from right to left one at a time: look at the rightmost, drop it, repeat; when the number is 0 you are done.