Reputation: 611
I am receiving a binary packet from a server containing the following:
var data = new Uint8Array([0xB2, 0xE2, 0xCA, 0xD4, 0x74, 0x65, 0x73, 0x74, 0x31, 0x32, 0x33]);
I know it's a GBK charset and I am using the TextDecoder/TextEncoder API to read it back:
var str = TextDecoder('gbk').decode(data);
// result: 测试test123
Now, the question : How to do the opposite ?
I tested :
var data = TextEncoder().encode(str);
// but it doesn't match
Some handed compression:
(str.charCodeAt(0) & 0xff) | ((str.charCodeAt(1) >>> 8) & 0xff)
// but yeah, not need to be pro to know it can't works.
Does someone know a way to do the reverse operation ? Thank you in advance.
Upvotes: 2
Views: 3651
Reputation: 611
Solved.
I used the shim: https://github.com/inexorabletash/text-encoding and commented a condition part in the TextEncoder constructor to allow other charset.
Here is an example:
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);
Upvotes: 1