js----hex(16进制)和字符串的互相转换

// hex转json字符串,16进制ASCII
var hextoString = function (hex) {
    var arr = hex.split("")
    var out = ""
    for (var i = 0; i < arr.length / 2; i++) {
        var tmp = "0x" + arr[i * 2] + arr[i * 2 + 1]
        var charValue = String.fromCharCode(tmp);
        out += charValue
    }
    return out
};

// json字符串转hex
var stringtoHex = function (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可以相互转换,直接将要转换的当做参数传进去,打印下就有值了。
使用例子:

// hextoString  demo
let str1 = '303132334041';
console.log(hextoString(str1));      //0123@A



//stringtoHex   demo
let str4 = '0123@A';
console.log(stringtoHex(str4));    //3031323340410a

参考:
https://www.runoob.com/jsref/jsref-obj-string.html

你可能感兴趣的:(Demo,JavaScript,hex与字符串互相转换)