Last active
December 7, 2018 09:25
-
-
Save keksipurkki/7ce6e14e891f8b60ef28826cf9a82f03 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env node | |
/** | |
./binarify.js < SOME_FILE > OUT_FILE | |
./binarify.js -d < OUT_FILE | |
*/ | |
const { Transform } = require("stream"); | |
const partition = (r,j) => r.reduce((a,b,i,g) => !(i % j) ? a.concat([g.slice(i,i+j)]) : a, []); | |
const octet = bits => bits.reduce((o, bit, index) => o + bit * (1 << (7 - index)), 0); | |
const encode = new Transform({ | |
transform: function transformer(chunk, encoding, callback) { | |
const binary = [...chunk].map(byte => byte.toString(2).padStart(8, "0")).join(""); | |
callback(false, binary); | |
} | |
}); | |
const decode = new Transform({ | |
transform: function transformer(chunk, encoding, callback) { | |
const bits = [...chunk].map(c => String.fromCharCode(c)).map(Number); | |
const bytes = partition(bits, 8).map(octet); | |
callback(false, Buffer.from(bytes)); | |
} | |
}); | |
const transform = process.argv[2] === "-d" ? decode : encode; | |
process.stdin.pipe(transform).pipe(process.stdout); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment