Last active
February 27, 2016 21:15
-
-
Save dchest/141d870f86fe681650a3 to your computer and use it in GitHub Desktop.
Simple XOR error correction demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Simple XOR error correction demo. | |
"use strict"; | |
const packets = [ | |
"hello world", | |
"JavaScript!", | |
"lose me plz", | |
"another one" | |
].map((s) => new Buffer(s)); | |
// We send all 4 packets... | |
const sentPackets = packets; | |
console.log('sent packets:', sentPackets.map(p => p.toString())); | |
// ...and one error correction packet, which is a XOR of all packets. | |
const correctionPacket = packets.reduce((p, c) => { | |
for (let i = 0; i < p.length; i++) { | |
p[i] ^= c[i]; | |
} | |
return p; | |
}, new Buffer(packets[0].length).fill(0)); | |
console.log('correction packet: ', correctionPacket.toString('hex')); | |
// Something loses one of our packets... | |
const lostPacket = packets[Math.floor(Math.random() * packets.length)]; | |
// ...and we receive only 3 packets and the error correction packaet. | |
const receivedPackets = sentPackets.filter(p => p !== lostPacket); | |
console.log('received packets:', receivedPackets.map(p => p.toString())); | |
// We can recover the lost packet by simply XORing all received | |
// packets with the correction packet. | |
const recoveredPacket = receivedPackets.reduce((p, c) => { | |
for (let i = 0; i < p.length; i++) { | |
p[i] ^= c[i]; | |
} | |
return p; | |
}, new Buffer(correctionPacket)); | |
// viola! | |
console.log('recovered packet: ', recoveredPacket.toString()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment