TextEncoder and TextDecoder not perfect inverses of each other

流过昼夜 提交于 2020-01-03 16:47:38

问题


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.


回答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);


来源:https://stackoverflow.com/questions/47296601/textencoder-and-textdecoder-not-perfect-inverses-of-each-other

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!