JS字符串转UTF8数组 - Mr.Ding

JS字符串转UTF8数组

天天记事 463 / 2021-12-26 12:58:35

直接上代码,仔细看

function stringToUtf8Array0(str) {
var utf8 = [], c = 0, c1 = 0;
for(var i = 0; i < str.length; i++) {
c = str.charCodeAt(i);
if(c < 0x80) {
utf8.push(c)
} else if(c < 0x800) {
utf8.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f))
} else if(c < 0xd800 || c >= 0xe000) {
utf8.push(0xe0 | (c >> 12), 0x80 | ((c>>6) & 0x3f), 0x80 | (c & 0x3f))
} else {
i++;
c1 = str.charCodeAt(i);
c = 0x10000 + (((c & 0x3ff)<<10) | (c1 & 0x3ff));
utf8.push(0xf0 | (c >>18), 0x80 | ((c>>12) & 0x3f), 0x80 | ((c>>6) & 0x3f), 0x80 | (c & 0x3f))
}
}
return utf8
}

function stringToUtf8Array1(str) {
var buf = encodeURI(str), len = buf.length, utf8 = [], c = 0;
for(var i = 0; i < len; i++) {
c = buf.charCodeAt(i);
if(c == 37) {
c = parseInt(buf.substr(i + 1, 2), 16);
i+=2
} else {
c = buf.charCodeAt(i)
}
utf8.push(c)
}
return utf8
}

function stringToUtf8Array2(str) {
var utf8 = [], i = 0, buf = unescape(encodeURIComponent(str)), len = buf.length;
for(; i < len; i++) {
utf8.push(buf.charCodeAt(i))
}
return utf8
}

function stringToUtf8Array3(str) {
var enbytes = new TextEncoder().encode(str), len = enbytes.length, utf8 = [], i = 0;
for(; i < len; i++) {
utf8.push(enbytes[i])
}
return utf8
}

function toHexStr(utf8arr) {
var hexstr = '', mod = 0, block = 32;
for(var i = 0; i < utf8arr.length; i++) {
mod = i % block;
if(i > 0) {
if(mod == 0) {
hexstr += '\n'
} else {
hexstr += ' '
}
}
hexstr += utf8arr[i].toString(16)
}
return hexstr
}


JSutf-8