Created
July 10, 2014 05:44
-
-
Save stupidbodo/323ffb4942693cc38709 to your computer and use it in GitHub Desktop.
Logical Exclusive Or VS Bitwise Exclusive Or - Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Exclusive or is a logical operation that outputs true whenever both inputs differ | |
# Truth Table | |
A = 0, B = 0, Output = 0 | |
A = 1, B = 0, Output = 1 | |
A = 0, B = 1, Output = 1 | |
A = 1, B = 1, Output = 0 | |
# Example of logical xor | |
# Logical xor evaluates expression logically(like how humans would read it) | |
# Output: True | |
a = 5 | |
b = 6 | |
bool(a) != bool(b) | |
# Example of bitwise xor | |
# Bitwise xor evaluates expression down to its binary/bit value | |
# Output: 3 | |
a = 5 | |
b = 6 | |
a ^ b | |
# How bitwise xor works in the background? | |
# First it converts the value into binary | |
bin(5)[2:] # '101' | |
bin(6)[2:] # '110' | |
# Now by evaluating xor on each bit, you will get '011' | |
# If you convert '011' back to number, you will get 3 | |
int('011',2) # 3 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment