所有都好用, 自然是用库

推荐的库是iconv, iconv-lite.
不过就是临时转一下, 还需要建一个npm项目不成? 有简单的办法吗?下面讲.

先说一个node.js和chrome兼容的做法: charCodeAt

'中文'.charCodeAt(0).toString(16) // "4e2d"
'中文'.charCodeAt(1).toString(16) // "6587"
'abc'..charCodeAt(0).toString(16) // "61"

这种方法得一个一个去取, 当然有个for循环会更方便
这个方法的逆方法是String.fromCharCode(new Uint16Array([0x6587])) ,打印出
这儿奇怪的是上述内容都是双字节编码...

chrome和firefox等浏览器实现了一个TextEncoder的类

只是这个类现在只支持utf8编码, 不再支持其他类型,如gbk.

var x = new TextEncoder().encode('中文')
//输出 Uint8Array(6) [228, 184, 173, 230, 150, 135]
(new Array(...x)).map(v=>v.toString(16)).join()
//"e4,b8,ad,e6,96,87"  上面先转普通数组, TypedArray不能用map将数字转为字符串, 然后再转16进制表示的字符串,再连接

逆类是TextDecoder, 这个支持gbk

new TextDecoder().decode(new Uint8Array([228, 184, 173, 230, 150, 135]))
//输出 "中文"
new TextDecoder('gbk').decode(new Uint8Array([0xd6,0xd0, 0xce, 0xc4]))
//输出 "中文"
(new TextDecoder('gbk')).decode(new Uint16Array([0xd6d0, 0xcec4]))
// "兄奈", 字节序问题, 这儿应该是小端字节序, 将字节反过来就对了
(new TextDecoder('gbk')).decode(new Uint16Array([0xd0d6, 0xc4ce]))
// "中文"

标签: none 阅读量: 1550

添加新评论