xor

Depe Lv1

What is XOR?

XOR (exclusive OR) is a logical operation used in computer science and cryptography.

  • It works bit by bit on two values.
  • Rule:
    • 0 ^ 0 = 0
    • 1 ^ 0 = 1
    • 0 ^ 1 = 1
    • 1 ^ 1 = 0

In short: the result is 1 only if the two bits are different.


Example (in binary)

1
2
3
4
5
1010 (decimal 10)  
^
0110 (decimal 6)
----
1100 (decimal 12)

So 10 ^ 6 = 12.


Why is XOR used in coding?

  • Reversible operation: If you XOR something twice with the same value, you get the original back.

Example:

1
2
3
4
x = 42
key = 99
encoded = x ^ key # encode
decoded = encoded ^ key # decode (original restored)

This makes XOR a common trick for simple encryption/obfuscation.


XOR with a Key

Instead of XORing with just a number (like 0x32), you can use a key (a number, string, or sequence).

Example with a single-number key:

1
2
3
4
5
message = "HELLO"
key = 23

encoded = [ord(c) ^ key for c in message] # encrypt
decoded = "".join(chr(c ^ key) for c in encoded) # decrypt

Example with a multi-character key:

If the key is longer (like a word), you usually repeat it across the message:

1
2
3
4
5
message = "HELLO"
key = "KEY"

encoded = [ord(c) ^ ord(key[i % len(key)]) for i, c in enumerate(message)]
decoded = "".join(chr(c ^ ord(key[i % len(key)])) for i, c in enumerate(encoded))

In Short

  • XOR is like a switch: same input = off (0), different input = on (1).

  • It’s reversible, which is why it’s used in encryption.

  • Using a key makes the XOR cipher stronger than just a fixed number.

  • Title: xor
  • Author: Depe
  • Created at : 2025-09-14 16:51:51
  • Updated at : 2025-09-14 17:01:36
  • Link: https://depe.blog/2025/09/14/xor/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments