觀看次數: 13,741
Operator | Description | Example |
& | Bitwise AND Operator | 8 & 29 = 8 |
| | Bitwise OR Operator | 8 | 29 = 29 |
^ | Bitwise XOR Operator | 8 ^ 29 = 21 |
<< | Bitwise Leftshift Operator | 8 << 1 = 16 |
>> | Bitwise Rightshift Operator | 8 >> 1 = 4 |
解說
- 8 (Decimal) = 01000 (Binary)
- 29 (Decimal) = 11101 (Binary)
- 8 & 29 -> 01000 & 11101 = 01000 -> 8
- 8 | 29 -> 01000 | 11101 = 11101 -> 29
- 8 ^ 29 -> 01000 ^ 11101 = 10101 -> 21
- 8 << 1 -> 01000 << 1 = 10000 -> 16
- 8 >> 1 -> 01000 >> 1 = 00100 -> 4
技巧 記巧
- & AND Bitwise Operator: 只要其中一個 bit 是 0,則結果為 0
- | OR Bitwise Operator: 只要其中一個 bit 是 1,則結果為 1
- ^ XOR Bitwise Operator: 兩個 bit 一樣 (0,0) 或(1,1) 則結果為 0,兩個bit不一樣則結果為1
重要性質
令 x 為一串bits,0s 代表與 x 同樣長度但所有bits皆為0,1s 代表皆為 1
AND & | x & 1s = x | x & 0s = 0s | x & x = x |
OR | | x | 1s = 1s | x | 0s = x | x | x = x |
XOR ^ (非常重要) | x ^ 1s = ~x | x ^ 0s = x | x ^ x = 0s |