JavaScript 中文转 GBK 编码并获取长度
function convertToGBK(str) { let bytes = []; for (let i = 0; i < str.length; i++) { let charCode = str.charCodeAt(i); if (charCode < 128) { bytes.push(charCode); } else { let highByte = (charCode >> 8) & 0xff; let lowByte = charCode & 0xff; bytes.push(highByte); bytes.push(lowByte); } } let length = bytes.length; console.log('GBK编码长度为:' + length); return bytes; }
// 示例 let str = '中文'; let gbkBytes = convertToGBK(str); // 将中文转换为GBK编码并输出长度 console.log(gbkBytes); // 输出 [167, 166, 184, 201]
原文地址: https://www.cveoy.top/t/topic/oLmE 著作权归作者所有。请勿转载和采集!