Table of contentsClick link to navigate to the desired location
This content has been automatically translated from Ukrainian.
XOR (exclusive OR) is a simple yet useful logical operation used in programming, cryptography, and data processing. It works on the principle that if two values are the same, the result will be 0, and if they are different – 1.
How does XOR look in practice?
Imagine you have two switches:
- If both are off – the light is off.
- If both are on – it is also off.
- But if one is on and the other is off – the light turns on.
This is how XOR works: if the elements are different – the result is 1, if they are the same – 0.
Where is XOR used?
Encryption – if you take text and XOR it with a key, you get an encrypted version. Repeating the XOR with the same key returns the original text. Bit manipulation – XOR helps in toggling individual bits in numbers. Difference checking – used in algorithms for comparing two sets of data.
In simple terms, XOR is like the rule "only one of two," which helps in many information processing tasks. Let's look at a simple example written in Ruby (ruby 3.4.2)
XOR Example (Ruby)
def xor_encrypt(text, key)
text.bytes.map.with_index { |char, i| char ^ key.bytes[i % key.size] }.pack('C*')
end
def xor_decrypt(encrypted_text, key)
xor_encrypt(encrypted_text, key)
end
text = "Hello, XOR!"
key = "key123"
encrypted = xor_encrypt(text, key)
puts "🔒 Encrypted: #{encrypted.inspect}"
decrypted = xor_decrypt(encrypted, key)
puts "🔓 Decrypted: #{decrypted}"
In the terminal, it will print something like this:
... 🔒 Encrypted: "#\x00\x15]]\x1FK=6c\x13" ... 🔓 Decrypted: Hello, XOR!
Here, each character of the text is combined with the key using XOR.Repeating the operation with the same key returns the original text.
This is one of the simplest encryption methods used in many algorithms.
This post doesn't have any additions from the author yet.