What does the caret operator (^) in Python do?

前端 未结 5 1774
忘了有多久
忘了有多久 2020-11-28 04:19

I ran across the caret operator in python today and trying it out, I got the following output:

>>> 8^3
11
>>> 8^4
12
>>> 8^1
9
>         


        
5条回答
  •  情话喂你
    2020-11-28 05:14

    It's a bitwise XOR (exclusive OR).

    It results to true if one (and only one) of the operands (evaluates to) true.

    To demonstrate:

    >>> 0^0
    0
    >>> 1^1
    0
    >>> 1^0
    1
    >>> 0^1
    1
    

    To explain one of your own examples:

    >>> 8^3
    11
    

    Think about it this way:

    1000  # 8 (binary)
    0011  # 3 (binary)
    ----  # APPLY XOR ('vertically')
    1011  # result = 11 (binary)
    

提交回复
热议问题