Python 教學:位元運算 (Bitwise Operation)

bokeh photography of yellow lights
OperatorDescriptionExample
&Bitwise AND Operator8 & 29 = 8
|Bitwise OR Operator8 | 29 = 29
^Bitwise XOR Operator8 ^ 29 = 21
<<Bitwise Leftshift Operator8 << 1 = 16
>>Bitwise Rightshift Operator8 >> 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 = xx & 0s = 0sx & x = x
    OR |x | 1s = 1sx | 0s = xx | x = x
    XOR ^ (非常重要)x ^ 1s = ~xx ^ 0s = xx ^ x = 0s
    scenic view of mountain during evening
    Photo by Drift Shutterbug on Pexels.com

    留言討論區