function stringToGBK(str) { let bytesCount = 0; for (let i = 0; i < str.length; i++) { const charCode = str.charCodeAt(i); if (charCode < 128) { bytesCount += 1; } else { bytesCount += 2; }
} return bytesCount; }

const chineseStr = '中文'; const bytesCount = stringToGBK(chineseStr); console.log('${chineseStr}' 的 GBK 编码长度为 ${bytesCount} 字节); // '中文' 的 GBK 编码长度为 4 字节

JavaScript 函数:计算中文字符串的 GBK 编码长度

原文地址: https://www.cveoy.top/t/topic/oLl2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录