如何计算字符的字节数

时间:2012-05-13 12:44:46

标签: javascript node.js

编辑:Ooooops。

console.log (Buffer.byteLength ("", "utf8")); //--> 3

我想计算一个字符的字节数。这就是我所拥有的:

var charBytesLength = function (c){
    var n = 0;
    c = c.charCodeAt (0);
    do{
        c = c >>> 8;
        n++;
    }while (c);
    return n;
};

如果字符使用UTF8编码,则对于超过2个字节的字符,函数始终返回2,因为在Javascript中,字符是16位值,charCodeAt()仅返回0到65535之间的值。 / p>

例如:

"".charCodeAt (0)

返回65533,当实际十六进制值为0x24065(十进制为147557)时

你知道如何计算实际字节数吗?

1 个答案:

答案 0 :(得分:2)

console.log (Buffer.byteLength ("", "utf8")); //--> 3