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?

thanks

Answers


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").

You may be able to set the page encoding to an 8-bit encoding like CP1252, which could (in some browsers, when the stars correctly align) coax the browser into using that same encoding when it encodes JavaScript strings… But that's not going to be guaranteed cross-browser compatible.

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, … ];

Need Your Help

$wpdb get_row populate session variable

php mysql wordpress wpdb

I am creating a custom login page for users on a website based on wordpress.

Why does a single record lookup return an array? (Rails beginner)

ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1

I have a where operation on a model that returns a single object. But I can't seem to use it in object notation (it appears to return an array with the object at [0]).