Bitwise operators and shifts [ref]
Problem
- Compute AND, OR, and XOR of
0b101 and 0b011.
- Shift
0b101 one position left and right.
- Test whether
5 is odd with a mask.
- Set bit
1 of 0b100.
- Clear the lowest set bit of
0b101100.
- Compute the two's-complement negation of
5 with ~.
Python solution
a, b = 0b101, 0b011
(a & b, a | b, a ^ b) # (1, 7, 6)
(a << 1, a >> 1) # (10, 2)
bool(5 & 1) # True
0b100 | (1 << 1) # 6
n = 0b101100
n & (n - 1) # 40, or 0b101000
~5 # -6; Python integers are not fixed-width
Links