Created
August 6, 2014 06:05
-
-
Save lihnux/2aa4a6f5a9170974f6aa to your computer and use it in GitHub Desktop.
Javascript Convert String to Byte 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
var url = "Hello World"; | |
var data = []; | |
for (var i = 0; i < url.length; i++){ | |
data.push(url.charCodeAt(i)); | |
} |
if you want to convert to array of numbers you could use
Array.from("1111222223333444445556", (x) => Number(x))
if you want to convert to array of numbers you could use
Array.from("1111222223333444445556", (x) => Number(x))
Array.from("\x00", (x) => Number(x))
results in [NaN]
!
If you handle raw bytes in a 0..255 space: Better use a slightly different version with charCodeAt
. I didnt test how it behaves with unicode chars.
Array.from("1111222223333444445556", , (x) => x.charCodeAt(0))
function unpack(str) { var bytes = []; for(var i = 0; i < str.length; i++) { var char = str.charCodeAt(i); bytes.push(char >>> 8); bytes.push(char & 0xFF); } return bytes; }
this is the correct way to extract the bytes a JavaScript string is made of
String.charCodeAt() returns a 16 bit unsigned integer, it must be split into two bytes if exceeds 0xff
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
also Array.from("111122222333344444555")