如何计算一个UTF-8编码的字符串究竟有多长?
- 内容介绍
- 文章标签
- 相关推荐
本文共计128个文字,预计阅读时间需要1分钟。
python计算字符串UTF-8表示的字节数def getByteLen(normal_val): # 强制将输入转换为字符串 normal_val=str(normal_val) # 计算字节数 byte_len=len(normal_val.encode('utf-8')) return byte_len
/** * Count bytes in a string's UTF-8 representation. * codereview.stackexchange.com/a/37552 * @param string * @return int */ function getByteLen(normal_val) { // Force string type normal_val = String(normal_val); var byteLen = 0; for (var i = 0; i < normal_val.length; i++) { var c = normal_val.charCodeAt(i); byteLen += c < (1 << 7) ? 1 : c < (1 << 11) ? 2 : c < (1 << 16) ? 3 : c < (1 << 21) ? 4 : c < (1 << 26) ? 5 : c < (1 << 31) ? 6 : Number.NaN; } return byteLen; }
本文共计128个文字,预计阅读时间需要1分钟。
python计算字符串UTF-8表示的字节数def getByteLen(normal_val): # 强制将输入转换为字符串 normal_val=str(normal_val) # 计算字节数 byte_len=len(normal_val.encode('utf-8')) return byte_len
/** * Count bytes in a string's UTF-8 representation. * codereview.stackexchange.com/a/37552 * @param string * @return int */ function getByteLen(normal_val) { // Force string type normal_val = String(normal_val); var byteLen = 0; for (var i = 0; i < normal_val.length; i++) { var c = normal_val.charCodeAt(i); byteLen += c < (1 << 7) ? 1 : c < (1 << 11) ? 2 : c < (1 << 16) ? 3 : c < (1 << 21) ? 4 : c < (1 << 26) ? 5 : c < (1 << 31) ? 6 : Number.NaN; } return byteLen; }

