Mohamed el bachir

XOR Tips – The Magic of Bitwise Operations

Discover the hidden magic of XOR (exclusive OR)—a bitwise operation that enables elegant solutions for swapping variables, encryption, and finding missing elem…

Mar 6, 2026

XOR Tips: The Bitwise Operation That Continues to Fascinate

XOR (exclusive OR) is one of those operations that seems simple on the surface but hides extraordinary power beneath. It's the kind of trick that makes experienced developers nod in recognition and has junior developers wondering, "How did they figure that out?"

Let's discover the magic.

Foundations: Understanding XOR

The XOR operation is wonderfully simple: it returns 1 when the bits are different, and 0 when they are the same.

  A     B     A ⊕ B  

  ---   ---   -----  

  0     0     0      

  0     1     1      

  1     0     1      

  1     1     0      

But this is where it gets interesting. XOR has a magical property that forms the basis of all these tricks:

The Self-Annihilation Property

a ⊕ b ⊕ b = a

This simple property is the key to everything. When you perform an XOR operation on a value with itself, it disappears. When you do it with something else, it reappears.

a = 5       (binaire: 101)
b = 3       (binaire: 011)

a ⊕ b = 6   (binaire: 110)
a ⊕ b ⊕ b = a ⊕ (b ⊕ b) = a ⊕ 0 = 5

Let's build something extraordinary with this property.

Tip #1: Find the Missing Number

Imagine you have the numbers 1 through 100, but one of them is missing. You also have a jumbled array where one number appears twice in place of the missing one. How do you figure out which number is missing and which one is duplicated?

The XOR Solution:

#include <stdio.h>

int xs[] = {7,62,2,46,73,43,26,82,5,95,57,56,44,21,40,79,13,6,9,8,72,59,65,81,60,78,13,85,87,58,48,25,32,47,67,4,31,19,33,1,92,14,53,89,84,54,29,10,17,3,77,70,45,97,34,23,86,55,15,64,68,83,76,41,18,39,94,22,74,11,69,49,12,35,20,90,100,98,36,63,91,38,66,93,50,96,61,71,75,37,52,88,30,28,99,27,42,51,80,24,16};

int main()
{
    int x = 0;

    // Faire un XOR de tous les nombres de 1 à 100
    for (int i = 1; i <= 100; ++i) {
        x ^= i;
    }

    // Faire un XOR de tous les nombres dans notre tableau
    size_t n = sizeof(xs)/sizeof(xs[0]);
    for (int i = 0; i < n; ++i) {
        x ^= xs[i];
    }

    // Le résultat est le nombre que nous cherchons !
    printf("%d\n", x);
    return 0;
}

How it works:

When you perform an XOR operation on all the numbers from 1 to 100, each number appears exactly once. When you do this with the array, the duplicates cancel each other out (because a ⊕ a = 0), leaving only the missing number.

It's like a magician who makes everything disappear except what was never there to begin with.

Tip #2: Secret Encryption With a Single Key

Need a simple encryption scheme? XOR has you covered.

def encrypt(m, k):
  return ''.join([chr(ord(a)^k) for a in m])

# Utilisation :
message = "Bonjour, le Monde !"
key = 42

encrypted = encrypt(message, key)
print(encrypted)  # Cela ressemble à du charabia

# Pour déchiffrer, chiffrez simplement à nouveau !
decrypted = encrypt(encrypted, key)
print(decrypted)  # "Bonjour, le Monde !"

Why does it work?

XOR is its own inverse. If you encrypt a message with a key, encrypting it again with the same key gives you the original message.

texte_clair ⊕ clé = texte_chiffré
texte_chiffré ⊕ clé = texte_clair

Important Note: This is perfect for simple obfuscation or learning purposes, but real cryptography requires much greater complexity. Do not use this to protect sensitive data!

Tip #3: XOR Chain List – The Magic of Memory

Do you want to traverse a linked list in both directions while storing half the pointers?

Welcome to the XOR linked list—a data structure that uses XOR as a memory trick:

#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>

typedef struct {
    int value;
    uintptr_t xored;  // Stocke : prev ^ next
} Node;

Node *node_create(int value)
{
    Node *node = malloc(sizeof(*node));
    node->value = value;
    node->xored = 0;
    return node;
}

typedef struct {
    Node *begin;
    Node *end;
} Linked_List;

void ll_append(Linked_List *ll, int value)
{
    if (ll->end == NULL) {
        ll->end = node_create(value);
        ll->begin = ll->end;
    } else {
        Node *node = node_create(value);
        node->xored     = (uintptr_t)ll->end;
        ll->end->xored ^= (uintptr_t)node;  // Mise à jour : prev ^ next
        ll->end         = node;
    }
}

Node *node_next(Node *node, uintptr_t *prev)
{
    Node *next = (Node*)(node->xored ^ (*prev));
    *prev = (uintptr_t)node;
    return next;
}

int main()
{
    Linked_List xs = {0};
    for (int x = 5; x <= 10; ++x) {
        ll_append(&xs, x);
    }

    uintptr_t prev = 0;
    for(Node *iter = xs.end; iter; iter = node_next(iter, &prev)) {
        printf("%d\n", iter->value);
    }

    return 0;
}

Each node stores prev ⊕ next instead of two pointers. To traverse the list, you XOR this value with the address of the previous node to get the next pointer.

Why? In systems with limited memory, this saves storage space. But in modern computing, it’s more of an elegant puzzle than a practical solution.

Tip #4: Swapping Two Variables Without Using a Temporary Variable

The classic tip for job interview questions:

#include <stdio.h>

int main()
{
    int a = 69;
    int b = 420;

    printf("Avant : %d %d\n", a, b);

    a ^= b;  // a = 69 ^ 420, b = 420
    b ^= a;  // b = 420 ^ (69 ^ 420) = 69
    a ^= b;  // a = (69 ^ 420) ^ 69 = 420

    printf("Après : %d %d\n", a, b);

    return 0;
}

Release date:

Avant : 69 420
Après : 420 69

How it works:

a ^= b transforms a into a container holding both values

b ^= a excerpt from the original a and stores it in b

a ^= b excerpt from the original b and stores it in a

Modern Note: Compilers are smart enough to optimize the simple approach using a variable temp, and it’s more readable. Use the XOR trick in interviews to impress, but in production code, keep it simple.

Why XOR Is Special

These tricks work because XOR has properties that few other operations share:

1. Self-annihilation: a ⊕ a = 0

2. Identity: a ⊕ 0 = a

3. Commutativity: a ⊕ b = b ⊕ a

4. Associativity: (a ⊕ b) ⊕ c = a ⊕ (b ⊕ c)

5. Inverse: XOR is its own inverse

These properties make XOR a powerful tool for bit manipulation, data processing, and algorithmic elegance.

Practical Applications Beyond Tips and Tricks

XOR isn't just for fun tricks. Real-world uses include:

Error Detection: XOR Checksums in Data Transmission

Cryptography: The basis for many encryption algorithms

Graphics: Toggle pixels without knowing their current state

Parity Check: Detecting single-bit errors in memory

Puzzles and Games: Efficient Management of In-Memory States

The Key Takeaway

XOR is a bitwise operation that demonstrates how understanding fundamental properties can lead to elegant solutions. Whether you’re finding missing numbers, encrypting messages, or impressing your colleagues during technical interviews, XOR remains one of the most versatile tools in a programmer’s toolkit.

The next time you see XOR in code, remember: it's not magic. It's mathematics that is beautifully and efficiently clever.

Ready to put these tips into practice? Start with the missing number problem—it’s the perfect introduction to appreciating the power of XOR.

Join 10 readers and get infrequent updates on new projects.

I promise not to spam you or sell your email address.

All systems normal

© 2026 Mohamed El Bachir. All rights reserved.