6

I received this answer to my previous question about encoding strings. My hope in asking that question was to get some reversible way of shifting between a string and its representation as an array of bytes like in Python 3.

I ran into a problem with one particular Uint8Array though:

var encoder = new TextEncoder();
var decoder = new TextDecoder(encoder.encoding);
var s = [248, 35, 45, 41, 178, 175, 190, 62, 134, 39];
var t = Array.from(decoder.decode(encoder.encode(Uint8Array(s)));

I expected the value of t to be [248, 35, 45, 41, 178, 175, 190, 62, 134, 39]. Instead, it is [239, 191, 189, 35, 45, 41, 239, 191, 189, 239, 191, 189, 239, 191, 189, 62, 239, 191, 189, 39]. The person who posted the answer was temporarily suspended from the site, so I cannot resolve this through commenting on his answer.

Melab
  • 2,594
  • 7
  • 30
  • 51
  • 2
    `s` does not refer to a string so your code doesn't match up to your question. _You aren't trying to process non-text data with a character encoding are you?_ `TextEncoder.encode` expects a string (a sequence of UTF-16 code units), not a `Uint8Array`. The code can be made to work, as @artgb did but there are some obscure coercions going on, including turning an array into a string to pass to `TextEncoder.encode`. – Tom Blodget Nov 16 '17 at 03:00
  • Possible duplicate of [Converting ArrayBuffer to String then back to ArrayBuffer using TextDecoder/TextEncoder returning a different result](https://stackoverflow.com/questions/50198017/converting-arraybuffer-to-string-then-back-to-arraybuffer-using-textdecoder-text) – zag2art Jun 28 '19 at 16:10

1 Answers1

1

change var t = Array.from(decoder.decode(encoder.encode(Uint8Array(s))); to
var t = JSON.parse('['+decoder.decode(encoder.encode(new Uint8Array(s)))+']');.

var encoder = new TextEncoder();
var decoder = new TextDecoder(encoder.encoding);
var s = [248, 35, 45, 41, 178, 175, 190, 62, 134, 39];
var t = JSON.parse('['+decoder.decode(encoder.encode(new Uint8Array(s)))+']');
console.log(t);
artgb
  • 3,177
  • 6
  • 19
  • 36