GBK编码/解码字符集



我从服务器收到一个包含以下内容的二进制数据包:

var data = new Uint8Array([0xB2, 0xE2, 0xCA, 0xD4, 0x74, 0x65, 0x73, 0x74, 0x31, 0x32, 0x33]);

我知道这是一个GBK字符集,我正在使用TextDecoder/TextEncoder API将其读回:

var str = TextDecoder('gbk').decode(data);
// result: 测试test123

现在,问题是:如何做相反的事情

我测试过:

var data = TextEncoder().encode(str);
// but it doesn't match

部分手动压缩:

(str.charCodeAt(0) & 0xff) | ((str.charCodeAt(1) >>> 8) & 0xff)
// but yeah, not need to be pro to know it can't works.

有人知道做反向操作的方法吗?提前谢谢。

已解决。

我使用了垫片:https://github.com/inexorabletash/text-encoding并对TextEncoder构造函数中的一个条件部分进行了注释,以允许其他字符集。

这里有一个例子:

if (this._encoding === null /*|| (this._encoding.name !== 'utf-8' &&
                                                                    this._encoding.name !== 'utf-16le' &&
                                                                    this._encoding.name !== 'utf-16be')*/)
throw new TypeError('Unknown encoding: ' + opt_encoding);

最新更新