5

I have a string that represents some binary data, looking like: \x89PNG\x1a\x00\x00\x00IHDR\x00\x00 etc

I need to post this string to some API, etc. AS IS but the problem is that Javascript automatically converts it to PNG etc

.escape, .encodeURI.. etc don't help

In Python such conversion can be done like string.encode('UTF-8') but I can't find nothing like that in JS.

Maybe someone knows the library or something that may help?

ElRey777
  • 191
  • 1
  • 12
  • How are you trying to upload it? It will need to be in a FormData, not a string. – Barmar Aug 07 '20 at 17:41
  • 1
    `string.encode("UTF-8")` is for binary data that contains text. PNG data is not text, encoding it as UTF-8 is not correct. – Barmar Aug 07 '20 at 17:42
  • @Barmar I do, the problem is that I need to add the encrypted signature to the Headers. The signature is generated from the whole data that I post, including the PNG. That's why I need this string – ElRey777 Aug 07 '20 at 17:49
  • Loop through the string calling `string.charCodeAt(i)` to get the numeric codes and calculate a signature. – Barmar Aug 07 '20 at 17:51
  • "*I have a string that represents some binary data*" - why are you not using a typed array / arraybuffer? And is the string `"\\x89PNG\\x1a\\x00\\x00\\x00IHDR\\x00\\x00"` or does it really contain the bytes as characters `"\x89PNG\x1a\x00\x00\x00IHDR\x00\x00"`? – Bergi Aug 09 '20 at 00:15
  • @Bergi just the strings, the question was how to turn it to something like the binary string – ElRey777 Aug 10 '20 at 14:48
  • @ElRey777 did you find any solutions to this? I'm also trying to create a sign, but the options I have tried in JS give a different result from python's string.encode('UTF-8') – Jumper Jun 20 '21 at 13:15
  • @Jumper no, unfortunately I couldn't so far... please share if you'll be more successful with that – ElRey777 Jul 07 '21 at 10:22

1 Answers1

1

In Javascript we usualy use Base64 for this.

You can do something like

var encodedData = window.btoa(stringToEncode);
var decodedData = window.atob(encodedData);

You may also find this interesting

function encode_utf8(s) {
  return unescape(encodeURIComponent(s));
}

function decode_utf8(s) {
  return decodeURIComponent(escape(s));
}

Or reference https://stackoverflow.com/a/22373061/6302200

Alex Cavazos
  • 621
  • 1
  • 5
  • 12