JavaScript “十六进制形式的字符串” 与 “字节数组” 相互转换

阿里云IoT设备对接,上传数据进行脚本解析的时候,有时候会用到hex和string的互转。
会用到下面的转化代码。

阿里云幸运卷,戳我领取!

function HexToString(bytes) {    //hex转string
    var ResultBuf = [];
    var len = 0;
    var hexlist = '0123456789abcdef';
    for (i = 0; i < bytes.length; i++) {

        ResultBuf[len] = hexlist.charCodeAt(bytes[i] / 16); len++;
        ResultBuf[len] = hexlist.charCodeAt(bytes[i] % 16); len++;

    }
    for (i = 0; i < len; i++) {
        bytes[i] = ResultBuf[i];
    }

    return bytes;
}
function StringToHex(bytes) {   //string转hex
    var uint8Array = new Uint8Array(bytes.length / 2);
    var buff = new Uint8Array(bytes.length);
    var hexABC = "0123456789ABCDEF";
    var hexabc = "0123456789abcdef";

    var i, j = 0;
    var point = 0;
    for (i = 0; i < bytes.length; i++) {
        buff[i] = bytes[i] & 0xff;

        for (j = 0; j < 16; j++) {
            if (buff[i] == hexABC.charCodeAt(j)) {
                buff[i] = j;
                break;
            }
            else if (buff[i] == hexabc.charCodeAt(j)) {
                buff[i] = j;
                break;
            }
            if (j == 15) {
                buff[i] = 0;
            }//超过f的字符都视为0
        }
    }
    for (i = 0; i < bytes.length / 2; i++) {
        uint8Array[i] = buff[point] * 16 + buff[point + 1];
        point += 2;
    }
    return uint8Array;
}

你可能感兴趣的:(阿里云,JavaScript,阿里云IoT,字符串,HEX,转换)