Created
May 16, 2014 07:01
-
-
Save mbaljeetsingh/3dfb5cf13daed13a3a46 to your computer and use it in GitHub Desktop.
Simple Encoder Decoder Javascript
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset=utf-8 /> | |
<title>Simple Encoder Decoder Javascript</title> | |
<style id="jsbin-css"> | |
</style> | |
</head> | |
<body> | |
<input type="text" name="inputCode" id="inputCode" value="Baljeet Singh Sandhu"> | |
<button onclick="clickMe()">clickMe</button> | |
<br> | |
<h1>Encoded Text:- <div id="encodedText"></div></h1> | |
<h1>Decoded Text:- <div id="decodedText"></div></h1> | |
<script> | |
var demoMemory = []; | |
function stringToArray(str) { | |
var i, | |
length = str.length, | |
arr = []; | |
for(i=0; i<length; i+=4) { | |
arr.push( | |
(((str.charCodeAt(i) || 0) << 24) | |
|((str.charCodeAt(i+1) || 0) << 16) | |
|((str.charCodeAt(i+2) || 0) << 8) | |
|((str.charCodeAt(i+3) || 0))) | |
); | |
} | |
if(length % 4 === 0) { | |
arr.push(0); | |
} | |
return arr; | |
} | |
function arrayToString(arr) { | |
var i, j, chrCode, | |
length = arr.length, | |
str = []; | |
label: | |
for(i=0; i<length; i++) { | |
for(j=24; j>=0; j-=8) { | |
chrCode = (arr[i] >> j) & 0xFF; | |
if(chrCode) { | |
str.push(String.fromCharCode(chrCode)); | |
} else { | |
break label; | |
} | |
} | |
} | |
return str.join(''); | |
} | |
function clickMe(){ | |
console.log(demoMemory = stringToArray(document.getElementById('inputCode').value)); // => [1936682341, 544437362, 1768843008] | |
console.log(arrayToString(demoMemory)); // "some string" | |
document.getElementById('encodedText').innerHTML = demoMemory; | |
document.getElementById('decodedText').innerHTML = arrayToString(demoMemory); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment