Skip to content

Instantly share code, notes, and snippets.

@stupidbodo
Created July 10, 2014 05:44
Show Gist options
  • Save stupidbodo/323ffb4942693cc38709 to your computer and use it in GitHub Desktop.
Save stupidbodo/323ffb4942693cc38709 to your computer and use it in GitHub Desktop.
Logical Exclusive Or VS Bitwise Exclusive Or - Python
# 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