Skip to content

Instantly share code, notes, and snippets.

@jhxxs
Last active April 4, 2022 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhxxs/d6cbd6ca0a0cf4bba561e9f525cbcf01 to your computer and use it in GitHub Desktop.
Save jhxxs/d6cbd6ca0a0cf4bba561e9f525cbcf01 to your computer and use it in GitHub Desktop.
等同于java的String.getBytes方法
function strToUtf8Bytes(str = '') {
const utf8: number[] = [];
for (let i = 0; i < str.length; i++) {
let 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 {
i++;
// Surrogate pair:
// UTF-16 encodes 0x10000-0x10FFFF by subtracting 0x10000 and
// splitting the 20 bits of 0x0-0xFFFFF into two halves
charCode = 0x10000 + (((charCode & 0x3ff) << 10) | (str.charCodeAt(i) & 0x3ff));
utf8.push(
0xf0 | (charCode >> 18),
0x80 | ((charCode >> 12) & 0x3f),
0x80 | ((charCode >> 6) & 0x3f),
0x80 | (charCode & 0x3f),
);
}
}
//兼容汉字,ASCII码表最大的值为127,大于127的值为特殊字符,【下面不必要,结果是有符号数,需要通过new Uint8Array()处理一次】
// for(let j=0; j<utf8.length; j++){
// const code = utf8[j];
// if(code>127){
// utf8[j] = code - 256;
// }
// }
return utf8;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment