二进制的魔法
取余 和 与
1. 与(&)的真面目
A | B | A&B |
---|---|---|
0 | 0 | 0 |
0 | 1 | 0 |
1 | 0 | 0 |
1 | 1 | 1 |
可以看出,在二进制的位运算中:
- 不管是 0 还是 1 ,& 1 的结果都是 本身
- 不管是 0 还是 1 ,& 0 的结果都是 0
1 & x = x x ∈ ( 0 , 1 ) ⇒ p e r s i s t 0 & x = 0 x ∈ ( 0 , 1 ) ⇒ r e s e t \begin{aligned} &1\ \&\ x=x\quad x\in(0,1)\Rightarrow persist\\ &0\ \&\ x=0\quad x\in(0,1)\Rightarrow reset \end{aligned} 1 & x=xx∈(0,1)⇒persist0 & x=0x∈(0,1)⇒reset
2. << 左移
假设,有 4 4 4 位二进制数 x 4 x 3 x 2 x 1 x_4x_3x_2x_1 x4x3x2x1 ,乘以 2 3 2^3 23
x 4 x 3 x 2 x 1 × 2 3 = ( x 4 ⋅ 2 3 + x 3 ⋅ 2 2 + x 2 ⋅ 2 1 + x 1 ⋅ 2 0 ) × 2 3 = x 4 ⋅ 2 6 + x 3 ⋅ 2 5 + x 2 ⋅ 2 4 + x 1 ⋅ 2 3 = x 4 x 3 x 2 x 1 000 \begin{aligned} &x_4x_3x_2x_1\times2^3\\ =&\ (x_4\cdot2^3 + x_3\cdot2^2 + x_2\cdot2^1 + x_1\cdot2^0)\times2^3\\ =&\ x_4\cdot2^6 + x_3\cdot2^5 + x_2\cdot2^4 + x_1\cdot2^3\\ =&\ x_4x_3x_2x_1000 \end{aligned} ===x