"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > What is the Caret Operator (^)?

What is the Caret Operator (^)?

Posted on 2025-03-25
Browse:896

What is the Caret Operator (^)?

Understanding the Caret (^) Operator in Python

The caret operator (^) in Python performs a bitwise exclusive OR (XOR) operation between its two operands. In other words, it evaluates to True if its arguments differ (one is True, the other is False) and evaluates to False if they are the same.

To demonstrate, consider the following examples:

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

Now, let's understand one of the examples you encountered:

>>> 8 ^ 3
11

This can be broken down into the following binary representation:

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

As you can see, the XOR operation is performed bit-by-bit, resulting in a binary value of 1011, which is equivalent to 11 in decimal.

Release Statement This article is reproduced on: 1729582995 If there is any infringement, please contact [email protected] to delete it.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3