https://www.cnblogs.com/han-guang-xue/p/14386666.html
1. Buffer 是用来处理流操作的
2. 字符串转化utf8字节数组, 然后在将字节数组转化十六进制字符串
/** 将字符串转化为utf-8字节 */
function ToUTF8(str) {var result = new Array();var k = 0;for (var i = 0; i < str.length; i++) {var j = encodeURI(str[i]);if (j.length == 1) {// 未转换的字符result[k++] = j.charCodeAt(0);} else {// 转换成%XX形式的字符var bytes = j.split("%");for (var l = 1; l < bytes.length; l++) {result[k++] = parseInt("0x" + bytes[l]);}}}return result;
}/** 将 byte 字节转化成十六进制 */
function Bytes2Str(arrBytes) {var str = ""for (var i = 0; i < arrBytes.length; i++) {var tmp;var num = arrBytes[i];if (num < 0) {//此处填坑,当byte因为符合位导致数值为负时候,需要对数据进行处理tmp = (255 + num + 1).toString(16);} else {tmp = num.toString(16);}if (tmp.length == 1) {tmp = "0" + tmp;}if (i > 0) {str += " " + tmp;} else {str += tmp;}}return str;
}/** 将十六进制字符串转化为 byte 数组 */
function Str2Bytes(name) {var hexA = new Array();name.forEach(item => {if (item === 'ff') {return hexA} else {hexA.push(parseInt(item, 16))}})return hexA
}
/** UTF8 转化为字符串 */
function UTF8ToStr(arr) {let val = ''arr.forEach(item => {if (item < 127) {val += String.fromCharCode(item)} else {val += '%' + item.toString(16).toUpperCase()}})console.log(val)try {return decodeURI(val)} catch (err) {return val}
}