Created
November 6, 2015 08:54
-
-
Save csauve/61de3ed5a5e203a5beb1 to your computer and use it in GitHub Desktop.
Given some ASCII input text, encodes it in the free codepoint bits of 3-byte unicode characters. Result is fewer characters but more bytes.
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
var TextEncoder = require("text-encoding").TextEncoder; | |
var TextDecoder = require("text-encoding").TextDecoder; | |
var jsSource = ""; | |
process.stdin.resume(); | |
process.stdin.on("data", function(buf) { | |
jsSource += buf.toString(); | |
}); | |
process.stdin.on("end", function() { | |
var encoded = encode(jsSource); | |
var decoded = decodeLite(encoded); | |
console.log(encoded); | |
if (decoded != jsSource) { | |
console.error("Mismatch detected. Try a different source."); | |
console.log(decoded); | |
} else { | |
console.log("Success!"); | |
} | |
}); | |
function encode(source) { | |
var inputBuffer = TextEncoder("utf-8").encode(source); | |
var outputBuffer = new Uint8Array(Math.ceil(inputBuffer.byteLength * 3 / 2)); | |
for (var i = 0, j=0; i < Math.ceil(inputBuffer.byteLength/2)*2;) { | |
var b1 = inputBuffer[i++]; | |
var b2 = inputBuffer[i++]; | |
outputBuffer[j++] = 0b11100000 | b1 >> 4 | |
outputBuffer[j++] = 0b10000000 | (b1 & 0b1111) << 2 | b2 >> 6 | |
outputBuffer[j++] = 0b10000000 | (b2 & 0b111111) | |
} | |
return TextDecoder("utf-8").decode(outputBuffer); | |
} | |
function decode(encoded) { | |
var inputBuffer = TextEncoder("utf-8").encode(encoded); | |
var outputBuffer = new Uint8Array(inputBuffer.byteLength * 2 / 3); | |
for (var i = 0, j=0; i < inputBuffer.byteLength;) { | |
var b1 = inputBuffer[i++]; | |
var b2 = inputBuffer[i++]; | |
var b3 = inputBuffer[i++]; | |
outputBuffer[j++] = (b1 & 0b1111) << 4 | (b2 & 0b111111) >> 2; | |
outputBuffer[j++] = b2 << 6 | (b3 & 0b111111); | |
} | |
return TextDecoder("utf-8").decode(outputBuffer); | |
} | |
function decodeLite(e) { | |
b=TextEncoder().encode(e); | |
o=new Uint8Array(b.length*2/3); | |
for (i=j=0;i<b.length;){o[j++]=(b[i++]&15)<<4|((y=b[i++])&63)>>2;o[j++]=y<<6|(b[i++]&63);} | |
return TextDecoder().decode(o); | |
} | |
/* Browser version: | |
data:text/html,<body onload='b=new TextEncoder().encode(decodeURIComponent(location.hash.slice(1)));o=new Uint8Array(b.length*2/3);for(i=j=0;i<b.length;){o[j++]=(b[i++]&15)<<4|((y=b[i++])&63)>>2;o[j++]=y<<6|(b[i++]&63);}eval(new TextDecoder().decode(o))'>#摯捵浥湴潤礮楮湥版呍䰠㴠≨敬汯Ⱐ睯牬搡∻ | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I ran this code and it made me a communist thanks op