← Back to blogs

Why XOR integer swapping feels like magic explain like im 5.

DEV BLOG · Integer Swapping · 16/10/25


> this blog assumes you have basic knowledge of programming and bitwise operations. > this is from my twitter thread https://x.com/forloopcodes/status/1978542908211872066

XOR Screenshot

### 0/n code, and simpler version

Step 0Simpler Version

### 1/n xor properties

> bitwise operator (https://www.geeksforgeeks.org/digital-logic/xor-gate/) > xor can be represented as the "^" character > A ^ B = B ^ A > A ^ (B ^ C) = (A ^ B) ^ C > A ^ A = 0 > A ^ 0 = A

Step 1

### 2/n step one

x = x ^ y

we simply assign the value of x ^ y to x

Step 2

### 3/n (you will need your last brain cells for this)

y = x ^ y

which means, y = (x ^ y) ^ y

while x = x ^ y

but now, y = (x ^ y) ^ y > y = x ^ (y ^ y) > y = x ^ 0 > y = x

yay we got our second number assigned the value of x!!!

Step 3

### 4/n the first value

third step: x = x ^ y

we already have x = x ^ y done in step 1, and y's value is x from step 2 so x = (x ^ y) ^ y(new) > x = (x ^ y) ^ x > x = (x ^ x) ^ y > x = 0 ^ y > x = y

damnit math

Step 4

### 5/n we finally got x = y and y = x with the fastest integer swap method known to mankind

good things > no bit overflow > fast af

if you want me to go deeper (bit by bit) ask me kindly 😼

Step 5

### yt (of someone else who might explain):

Link: The XOR Swap

follow me on x dot com for more