Convert an integer to a string of bytes

I have a variable, call it myNum , which contains a 32-bit value. I would like to turn it into a 4-byte string, where each byte of the string corresponds to a part of myNum .

I am trying to do something like the following (which does not 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 350, then str would look like 0x00 , 0x00 , 0x01 , 0x5e when I examine it in wirehark.

charCodeFrom() does just what I want, when every single byte has a value <= 0x7f. Is there a browser independent way to do what I'm trying to do?

thanks

+4
source share
1 answer

In short: you cannot.

Longer: this is because any character in a string with a value> = 0x80 will be encoded as unicode using the default encoding of the browser (maybe UTF-8, but sometimes you will find a browser that selects something β€œrandom”). For example, if you send a "byte" with a value of \x80 , you will most likely see \xC2\x80 on the explorer (`` \ xC2 \ x80 ".decode (" utf-8 ") == u" \ u0080 ") .

You may be able to set the page encoding to 8-bit encoding, such as CP1252, which can (in some browsers when the stars align correctly) coax the browser using the same encoding when it encodes JavaScript strings ... But this Cross-browser compatibility not guaranteed.

Some more reliable options may be:

  • Configure the endpoint to decode the strings coming from JS as unicode, then transcode them as bytes (in Python it will 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, … ];
+3
source

Source: https://habr.com/ru/post/1433032/


All Articles