Created
January 30, 2019 21:34
-
-
Save raphaelchaib/0eb1bebd5142eab4b099159d3d35d22a to your computer and use it in GitHub Desktop.
Javascript: String to Bytes array
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
stringToBytes('this is a test'); | |
function stringToBytes(str) { | |
var ch, st, re = []; | |
for (var i = 0; i < str.length; i++ ) { | |
ch = str.charCodeAt(i); // get char | |
st = []; // set up "stack" | |
do { | |
st.push( ch & 0xFF ); // push byte to stack | |
ch = ch >> 8; // shift value down by 1 byte | |
} | |
while ( ch ); | |
// add stack contents to result | |
// done because chars have "wrong" endianness | |
re = re.concat( st.reverse() ); | |
} | |
// return an array of bytes | |
return re; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment