{"slug": "bitwise-and-otherwise-understanding-xor-distance", "title": "Bitwise and Otherwise: Understanding XOR Distance", "summary": "Developer Maneshwar explains XOR distance, a metric used in peer-to-peer networks like Kademlia, in a technical blog post. The post breaks down how XOR distance is computed, why it qualifies as a proper distance metric, and how it underpins routing tables in systems like BitTorrent's DHT, IPFS, and Ethereum. It includes code examples and a bucket_index function to illustrate how nodes organize peers by distance.", "body_md": "*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.*\n\nI knew XOR.\n\nTruth tables, bit flips, the whole deal, nothing new there.\n\nThen I was reading some article about P2P networking and ran into the phrase \"XOR distance\" and just kind of stopped.\n\nXOR I know. Distance I know. XOR *distance*? That's not a thing, that's two things wearing a trenchcoat.\n\nSo 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.\n\nSo let's do this properly.\n\nWe're going to talk about bits, buckets, and why your node's \"neighbors\" have nothing to do with where they physically live.\n\nXOR distance between two IDs is just: XOR their bits together, read the result as a number.\n\nThat number is your \"distance.\"\n\nBigger number, farther apart.\n\nSmaller number, closer.\n\nThat's it. That's the tweet.\n\nObviously that's not satisfying, so let's actually build it up.\n\nXOR (exclusive or) looks at two bits and asks one question: \"do you two agree?\"\n\n| A | B | A XOR B |\n|---|---|---|\n| 0 | 0 | 0 |\n| 0 | 1 | 1 |\n| 1 | 0 | 1 |\n| 1 | 1 | 0 |\n\nSame bits, you get 0.\n\nDifferent bits, you get 1.\n\nXOR is basically the \"spot the difference\" operator of computer science.\n\nNow 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):\n\n```\nA = 1100\nB = 1010\n    ----\n    0110   (this is the XOR)\n```\n\nRead `0110`\n\nas a plain binary number and you get 6.\n\nSo distance(A, B) = 6.\n\nCongrats, you just computed an XOR distance by hand, you can put that on your resume now.\n\nMath is picky about the word \"distance.\"\n\nFor 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.\n\nThat third property is the whole reason this isn't just a cute math trick, it's what makes routing *converge*.\n\nHere's the part that trips people up.\n\nXOR distance isn't \"count how many bits differ\" (that's Hamming distance, a different and much less useful cousin).\n\nXOR distance cares about *where* the differing bits are, because it's read as a number, and in numbers, the leftmost digit matters way more than the rightmost one.\n\n```\n1000 XOR 0000 = 1000 = 8   <- disagree on the leftmost (high) bit\n0000 XOR 0001 = 0001 = 1   <- disagree on the rightmost (low) bit\n```\n\nBoth pairs differ in exactly one bit.\n\nOne of them is 8x \"farther\" than the other.\n\nSame amount of disagreement, wildly different distance, all because of *where* the disagreement lives.\n\nHere's roughly how that feels, emotionally:\n\nEnough theory, let's compute this for real:\n\n``` php\ndef xor_distance(a: int, b: int) -> int:\n    return a ^ b\n\ndef bucket_index(distance: int) -> int:\n    \"\"\"Which 'bucket' this distance falls into, i.e. index of the\n    highest set bit. This is the thing Kademlia uses to organize\n    its routing table.\"\"\"\n    return distance.bit_length() - 1 if distance else -1\n\nA = 0b1100\nB = 0b1010\nC = 0b1101\n\nprint(xor_distance(A, B))        # 6  -> pretty far\nprint(xor_distance(A, C))        # 1  -> very close\nprint(bucket_index(xor_distance(A, B)))  # 2\nprint(bucket_index(xor_distance(A, C)))  # 0\n```\n\nThe `bucket_index`\n\nfunction is the sneaky important part.\n\nIt tells you *how far* in terms of \"shared prefix length.\"\n\nA distance that falls in a high bucket means the IDs barely agree on anything at the front.\n\nA distance in bucket 0 means they agree on almost everything except the last bit.\n\nThis bucketing is literally how Kademlia (the algorithm behind BitTorrent's DHT, IPFS, and Ethereum's node discovery) organizes who a node bothers to remember.\n\nEvery node keeps a set of buckets, one per \"distance range,\" and each bucket holds a few peers at that rough distance. Think of it like this:\n\nYou keep detailed, well-maintained knowledge of nodes close to you, and increasingly fuzzy, \"eh, good enough\" knowledge of nodes far away.\n\nIt's basically how your own brain works with acquaintances: you remember your best friend's birthday, you remember that one guy from a conference exists.\n\nSay you want to find the node closest to some target ID `T`\n\n, and you're not there yet.\n\nYou ask whoever you currently know that's closest to `T`\n\n.\n\nThey, in turn, know someone closer to `T`\n\nthan you do (because of how the buckets are structured), and they hand you that contact. Repeat.\n\nBecause of the triangle inequality, each hop is guaranteed to strictly shrink your distance to `T`\n\n.\n\nIn practice this converges in roughly O(log n) hops for a network of `n`\n\nnodes, because each hop tends to fix another bit of agreement with the target.\n\nNo coordinates, no GPS, no \"which continent is this peer even on,\" just pure bit math.\n\nThis is the bit that messes with people's intuition the most, because we're all trained to think \"distance\" means physical distance.\n\nA node in Bengaluru and a node in Reykjavik can have a *tiny* XOR distance if their hashed IDs happen to share a long bit prefix, purely by coincidence of hashing.\n\nMeanwhile two servers sitting in the same rack can be maximally far apart in XOR space if their IDs hash unluckily.\n\nAnd honestly, that's kind of the whole point. XOR distance throws away geography entirely and replaces it with something that's provably well behaved for routing, at the cost of being completely unintuitive to a human looking at a map. Worth it.\n\nIf you want to go further down the hole:\n\nXOR distance isn't really \"distance\" in any sense your GPS would recognize, it's a purpose-built mathematical ruler that happens to satisfy exactly the properties routing needs: zero self-distance, symmetry, and a triangle inequality that guarantees convergence.\n\nOnce that clicks, a huge chunk of how DHTs work stops feeling like magic and starts feeling like, well, bit flips with really good manners.\n\nAnyway, that's XOR distance. Go forth and route responsibly.\n\nAI agents write code fast. They also silently remove logic, change behavior, and introduce bugs — without telling you. You often find out in production.\n\ngit-lrc fixes this. It hooks into git commit and reviews every diff before it lands. 60-second setup. Completely free.\n\nAny feedback or contributors are welcome! It's online, source-available, and ready for anyone to use.\n\n⭐ Star it on GitHub:\n\n| [🇩🇰 Dansk](https://github.com/HexmosTech/git-lrc/readme/README.da.md) | [🇪🇸 Español](https://github.com/HexmosTech/git-lrc/readme/README.es.md) | [🇮🇷 Farsi](https://github.com/HexmosTech/git-lrc/readme/README.fa.md) | [🇫🇮 Suomi](https://github.com/HexmosTech/git-lrc/readme/README.fi.md) | [🇯🇵 日本語](https://github.com/HexmosTech/git-lrc/readme/README.ja.md) | [🇳🇴 Norsk](https://github.com/HexmosTech/git-lrc/readme/README.nn.md) | [🇵🇹 Português](https://github.com/HexmosTech/git-lrc/readme/README.pt.md) | [🇷🇺 Русский](https://github.com/HexmosTech/git-lrc/readme/README.ru.md) | [🇦🇱 Shqip](https://github.com/HexmosTech/git-lrc/readme/README.sq.md) | [🇨🇳 中文](https://github.com/HexmosTech/git-lrc/readme/README.zh.md) | [🇮🇳 हिन्दी](https://github.com/HexmosTech/git-lrc/readme/README.hi.md) |\n\nGenAI today is a **race car without brakes**. It accelerates fast -- you describe something, and large blocks of code appear instantly. But AI agents *silently break things*: they remove logic, relax constraints, introduce expensive cloud calls, leak credentials, and change behavior -- without telling you. You often find out in production.\n\n** git-lrc is your braking system.** It hooks into\n\n`git commit`\n\nand runs an AI review on every diff In short, git-lrc helps **Prevent Outages, Breaches, and Technical Debt Before They Happen**\n\n**At a glance:** [10 risk categories](https://github.com/HexmosTech/git-lrc#what-git-lrc-checks-for) · [100+ failure patterns tracked](https://github.com/HexmosTech/git-lrc#what-git-lrc-checks-for) · every commit…", "url": "https://wpnews.pro/news/bitwise-and-otherwise-understanding-xor-distance", "canonical_source": "https://dev.to/lovestaco/bitwise-and-otherwise-understanding-xor-distance-1kh8", "published_at": "2026-08-25 18:43:57+00:00", "updated_at": "2026-08-25 19:14:54.524359+00:00", "lang": "en", "topics": ["developer-tools"], "entities": ["Maneshwar", "git-lrc", "Kademlia", "BitTorrent", "IPFS", "Ethereum"], "alternates": {"html": "https://wpnews.pro/news/bitwise-and-otherwise-understanding-xor-distance", "markdown": "https://wpnews.pro/news/bitwise-and-otherwise-understanding-xor-distance.md", "text": "https://wpnews.pro/news/bitwise-and-otherwise-understanding-xor-distance.txt", "jsonld": "https://wpnews.pro/news/bitwise-and-otherwise-understanding-xor-distance.jsonld"}}