问题描述
我收到了我以前有关编码字符串的问题的。我希望问这个问题是为了获得一种可逆的方式,在字符串及其表示为字节数组的表示形式之间进行转换,就像在Python 3中一样。
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.
我遇到了一个问题但是使用一个特定的Uint8Array:
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)));
我希望 t
的值是 [248,35,45,41,178,175,190,62,134 ,39]
。相反,它是 [239,191,189,35,45,41,239,191,189,239,191,189,239,191, 189,62,239,191,189,39]
。发布答案的人被暂时从网站暂停,所以我无法通过评论他的答案来解决这个问题。
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.
推荐答案
change var t = Array.from(decoder.decode(encoder.encode(Uint8Array(s)));
到
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);
这篇关于TextEncoder和TextDecoder互不完美的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!