Skip to content

Instantly share code, notes, and snippets.

@samuelmaddock
Last active August 5, 2017 17:45
Show Gist options
  • Save samuelmaddock/d7ad828251ad3df98449 to your computer and use it in GitHub Desktop.
Save samuelmaddock/d7ad828251ad3df98449 to your computer and use it in GitHub Desktop.
JavaScript Whitespace Encode/Decode
var source = 'hello world';
function whitespaceEncode(str) {
var j, result = '';
for (var i = 0; i < str.length; i++) {
var charCode = str.charCodeAt(i);
var binStr = charCode.toString(2);
var padLen = 7 - (binStr.length % 7);
for (j = 0; j < padLen; j++) {
binStr = '0' + binStr;
}
for (j = 0; j < binStr.length; j++) {
result += (binStr[j] === '0') ?
' ' : // space
' '; // tab
}
}
return result;
}
function whitespaceDecode(str) {
var result = '';
str.replace(/.{7}/g, function (strByte) {
var binStr = strByte.replace(/ /g, '0').replace(/ /g, '1');
var charCode = parseInt(binStr, 2);
result += String.fromCharCode(charCode);
});
return result;
}
var encodedSource = whitespaceEncode(source);
var decodedSource = whitespaceDecode(encodedSource);
console.log('SOURCE:', source);
console.log('ENCODED:', encodedSource);
console.log('DECODED:', decodedSource);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment