Bitwise and Otherwise: Understanding XOR Distance
Hello, I'm Maneshwar. I'm building git-lrc, a Micro AI code reviewer that runs on every commit. It is free and source-available on Github. Star git-lrc to help devs discover the project. Do give it a try and share your feedback. I knew XOR. Truth tables, bit flips, the whole deal, nothing new there. Then I was reading some article about P2P networking and ran into the phrase "XOR distance" and just kind of stopped. XOR I know. Distance I know. XOR distance ? That's not a thing, that's two things wearing a trenchcoat. So I went and actually learned how it works, and it turns out it's one of those ideas that's simple once it clicks and mildly infuriating right up until it does. So let's do this properly. We're going to talk about bits, buckets, and why your node's "neighbors" have nothing to do with where they physically live. The one-line version XOR distance between two IDs is just: XOR their bits together, read the result as a number. That number is your "distance." Bigger number, farther apart. Smaller number, closer. That's it. That's the tweet. Obviously that's not satisfying, so let's actually build it up. Step 1: what XOR even does XOR (exclusive or) looks at two bits and asks one question: "do you two agree?" A B A XOR B 0 0 0 0 1 1 1 0 1 1 1 0 Same bits, you get 0. Different bits, you get 1. XOR is basically the "spot the difference" operator of computer science. Now take two IDs (in real systems these are 160-bit or 256-bit hashes, but let's use 4 bits so nobody has to squint): A = 1100 B = 1010 ---- 0110 (this is the XOR) Read 0110 as a plain binary number and you get 6. So distance(A, B) = 6. Congrats, you just computed an XOR distance by hand, you can put that on your resume now. Step 2: why we're even allowed to call this a "distance" Math is picky about the word "distance." For something to count as a proper metric, it needs three properties, and XOR happens to nail all three, which honestly feels like a happy accident but isn't. distance(A, A) = 0. An