Bit Magic
- negative numbers are represented in 2's complement in most languages
- Range: [-2 n-1 to 2 n-1 - 1]; n - number of bits
- Range for unsigned:
- 2's complement - 1. invert all bits; 2. add 1
info
leading bit is 1 for negative numbers
Bitwise Operators
- Bitwise AND: &
- Bitwise OR: |
- Bitwise XOR : ^
| A | B | & | | | ^ |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 1 | 1 |
| 1 | 0 | 0 | 1 | 1 |
| 1 | 1 | 1 | 1 | 0 |
- Bitwise Not: ~
- Python
x = 5 # 0...0101
print(~x) # -6 # 1...1010
Shift Operators
- Left Shift: <<
- Right Shift: >>
- Python
x=5 # 101
x << 2 # 10100
x >> 3 # 000
x << n # x * 2^n
1 << n # 2^n