16进制和字符串互相转换

梦想与她 提交于 2019-12-21 05:13:55

16进制字符串转字符串[hex]

// 16进制转字符串
  hexToString: function(value) {
    let arr = this.groupArray(value), //将16进制字符串进行每两个分组
      result = "";
    for (var i = 0; i < arr.length; i++) {
      result += String.fromCharCode(parseInt(arr[i], 16)); //将分组后的16进制字符串转10进制Unicode码,然后将Unicode码转换为字符
    }
    return result
  },
  groupArray: function(str) {
    let result = new Array();
    for (let i = 0; i < str.length / 2; i++) {
      var currentValue = str.slice(i * 2, (i + 1) * 2);`在这里插入代码片`
      result.push(currentValue);
    }
    return result;
  },

字符串转16进制字符串[string]

/**
     * 转成ascii码数组
     */
    function hexToArray(hexStr) {
      var words = [];
      var hexStrLength = hexStr.length;

      if (hexStrLength % 2 !== 0) {
        hexStr = leftPad(hexStr, hexStrLength + 1);
      }

      hexStrLength = hexStr.length;

      for (var i = 0; i < hexStrLength; i += 2) {
        words.push(parseInt(hexStr.substr(i, 2), 16)); 
      }
      return words;
    }
    /**
     * 转成16进制串
     */
    function arrayToHex(arr) {
      var words = [];
      var j = 0;
      for (var i = 0; i < arr.length * 2; i += 2) {
        words[i >>> 3] |= parseInt(arr[j], 10) << 24 - i % 8 * 4;
        j++;
      }

      // 转换到16进制
      var hexChars = [];
      for (var _i2 = 0; _i2 < arr.length; _i2++) {
        var bite = words[_i2 >>> 2] >>> 24 - _i2 % 4 * 8 & 0xff;
        hexChars.push((bite >>> 4).toString(16));
        hexChars.push((bite & 0x0f).toString(16));
      }

      return hexChars.join('');
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!