前段时间遇到一个奇葩问题,是一个朋友问如何将一段16进制的串转为 json字符串。虽然网上有好多类似的答案,但是都不太满足需求,于是总结整理了一番,在这里给大家分享一下。
json字符串转hex
stringtoHex (str) {
var val = "";
for (var i = 0; i < str.length; i++) {
if (val == "")
val = str.charCodeAt(i).toString(16);
else
val += str.charCodeAt(i).toString(16);
}
val += "0a"
return val
}
hex转json字符串,16进制ASCII
async hextoString (hex) {
var arr = hex.split(""),
out = "",
len = str.length/2;
for(var i = 0; i < len; i++){
out += String.fromCharCode(parseInt(str.substr(i*2,2),16));
}
// 解决乱码问题
return await this.utf8to16(val)
};
ok,还没完
json有可能有中文,会出现乱码问题
utf8to16(str) {
var out, i, len, c;
var char2, char3;
out = "";
len = str.length;
i = 0;
while(i < len) {
c = str.charCodeAt(i++);
switch(c >> 4){
case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
out += str.charAt(i-1);
break;
case 12: case 13:
char2 = str.charCodeAt(i++);
out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
break;
case 14:
char2 = str.charCodeAt(i++);
char3 = str.charCodeAt(i++);
out += String.fromCharCode(((c & 0x0F) << 12) |
((char2 & 0x3F) << 6) |
((char3 & 0x3F) << 0));
break;
}
}
console.log(out,'最终值')
return out
}