Last active
August 5, 2017 17:45
-
-
Save samuelmaddock/d7ad828251ad3df98449 to your computer and use it in GitHub Desktop.
JavaScript Whitespace Encode/Decode
This file contains hidden or 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 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