-
-
Save rangercyh/f2b5a31c9b99388282661be0cdfa85a1 to your computer and use it in GitHub Desktop.
unicode字符串求utf8字节长度:https://segmentfault.com/a/1190000005794963
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let sizeof = function(str) { | |
let total = 0, charCode, i, len | |
for (i = 0, len = str.length; i < len; i++) { | |
charCode = str.charCodeAt(i) | |
if (charCode <= 0x007f) { | |
total += 1 | |
} else if (charCode <= 0x07ff) { | |
total += 2 | |
} else if (charCode <= 0xffff) { | |
total += 3 | |
} else if (charCode <= 0x1fffff) { | |
total += 4 | |
} else if (charCode <= 0x3ffffff) { | |
total += 5 | |
} else { | |
total += 6 | |
} | |
} | |
return total | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let get_send_string = function(str) { | |
let total = 0, charCode, i, len, back = [] | |
for (i = 0, len = str.length; i < len; i++) { | |
charCode = str.charCodeAt(i) | |
if (charCode <= 0x007f) { | |
total += 1 | |
back.push(charCode) | |
} else if (charCode <= 0x07ff) { | |
total += 2 | |
back.push((192 | (31 & (charCode >> 6)))) | |
back.push((128 | (63 & charCode))) | |
} else { | |
total += 3 | |
back.push((224 | (15 & (charCode >> 12)))); | |
back.push((128 | (63 & (charCode >> 6)))); | |
back.push((128 | (63 & charCode))) | |
} | |
} | |
for (i = 0; i < back.length; i++) { | |
back[i] &= 0xff | |
} | |
if (total <= 0xff) { | |
return new Uint8Array([0, total].concat(back)) | |
} else { | |
return new Uint8Array([total >> 8, total & 0xff].concat(back)) | |
} | |
} | |
get_send_string(chunk).buffer instanceof ArrayBuffer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment