您可以使用这个函数(
gist):
function toUTF8Array(str) {
var utf8 = [];
for (var i=0; i < str.length; i++) {
var charcode = str.charCodeAt(i);
if (charcode < 0x80) utf8.push(charcode);
else if (charcode < 0x800) {
utf8.push(0xc0 | (charcode >> 6),
0x80 | (charcode & 0x3f));
}
else if (charcode < 0xd800 || charcode >= 0xe000) {
utf8.push(0xe0 | (charcode >> 12),
0x80 | ((charcode>>6) & 0x3f),
0x80 | (charcode & 0x3f));
}
else {
utf8.push(0xef, 0xbf, 0xbd);
}
}
return utf8;
}
使用示例:
>>> toUTF8Array("中€")
[228, 184, 173, 226, 130, 172]
如果你希望像Java的字节转整数一样,对于大于127的值使用负数,那么你需要调整常量并使用
utf8.push(0xffffffc0 | (charcode >> 6),
0xffffff80 | (charcode & 0x3f));
并且
utf8.push(0xffffffe0 | (charcode >> 12),
0xffffff80 | ((charcode>>6) & 0x3f),
0xffffff80 | (charcode & 0x3f));
"中".getBytes("UTF8")
得到的是{-28, -72, -83}
,但是答案中的函数却得到了[78, 45]
。 - ivkremer0
是每个16位代码单元的上半部分。当按照UTF-8方案编码时,那个汉字字符需要3个字节,而通过UTF-16只需要2个字节。 - obataku