Convert an integer to a string of bytes
I've got a variable, let's call it myNum, containing a 32-bit value. I'd like to turn it into a 4-byte string where each byte of the string corresponds to part of myNum.
I'm trying to do something like the following (which doesn't work):
var myNum = someFunctionReturningAnInteger(); var str = ""; str += String.charCodeFrom((myNum >>> 24) & 0xff); str += String.charCodeFrom((myNum >>> 16) & 0xff); str += String.charCodeFrom((myNum >>> 8) & 0xff); str += String.charCodeFrom(myNum & 0xff);
For example, if myNum was equal to 350 then str would look like 0x00,0x00,0x01,0x5e when I examine it in wireshark.
charCodeFrom() only does what I want when each individual byte has a value <= 0x7f . Is there a browser-independent way to do what I'm trying to do?
In short: you can't.
In longer: this is happening because any character in a string with a value >= 0x80 will be encoded as unicode using the browser's default encoding (probably UTF-8, but occasionally you'll find a browser which pick something "random"). For example, if you send a "byte" with the value \x80, you'll likely see \xC2\x80 on the wire (`"\xC2\x80".decode("utf-8") == u"\u0080").
Some more reliable options might be:
- Setup the end point to decode the strings coming from JS as unicode, then re-encode them as bytes (in Python, it would be something like "".join(chr(ord(ub)) for ub in your_unicode_string))
- Send the "bytes" as an array of integers: var bytes = [ (myNum >> 24) & 0xFF, … ];