4 odpowiedzi
+ 6
Hi Ruslan Guliyev !
XOR is used as an bitewise operator. Bitewise operators can be uesed when you want get a special output of two inputed values that is either high or low, ones or zeros, true or false.
For XOR, the exclusive OR, both input values must be different to get the output true, otherwise false; you really have to choose between two things, but not both!
So in real world it is used in programming or when you are working with electronic circuts.
Take a look this video. It explains how XOR can be used as a logical gate, among the other logical operators:
https://youtu.be/lXWpWNKwYbo
And here an explaination in text about how bitwise operators works in Python:
https://realpython.com/python-bitwise-operators/#why-use-binary
+ 3
Not only in Python but in general, I use XOR frequently as a flip flop to toggle between two values without using an if statement.
Example, a Boolean flag that holds alternating 0 or 1:
flag ^= 1 #toggle to its opposite value
A bit flipper - change case of a letter by toggling bit 5:
letter ^= 32 # make a -> A, or A -> a
Encoding/Encryption
This is a bigger topic than I will address here, but XOR provides a tricky way to store two values at once in a single storage space:
a = 6^5 # (equals 3)
print(a^5, a^6) #Output: 6 5
I believe there are always other means to do the same thing as XOR, so it is not compelling to use it. In Boolean logic it is the same relation as !=.
+ 2
Let's Take the example, we have an Input form:
Player: XXOXXOX
Enemy:XOXOXXO
We've a swordsman turnement X-marks every Round where a swordsman hits his enemy.
When both have an X means it's a Draw and we just want the Points where either the Player or enemy won, also for Input:
XXXXOXOO
XOXOXOXX
Would we give out the Points 3:3.
+ 1
Thank you very much for your answers and contribution!