JS CRC16/XMODEM




const byteData= HexString2Bytes("1A3B4C5D")
let crc = crc16(byteData)
// CRC转换: A185
console.log("CRC转换:",crc)

function crc16(buffer) {
  var crc = 0x0000;
  var odd;

  for(var i = 0; i < buffer.length; i++) {
    crc ^= (buffer[i] << 8)
    for(var j = 0; j < 8; j++) {
      odd = crc & 0x8000;
      crc = crc << 1;
      if(odd) {
        crc = crc ^ 0x1021
      }
    }
  }

  var hi = ((crc & 0xFF00) >> 8); //高位置
  var lo = (crc & 0x00FF); //低位置
  var crcArr = []
  crcArr.push(hi)
  crcArr.push(lo)
  crc &= 0xFFFF
  return crcToString(crcArr, true)
};    

//转为大写String
function crcToString(arr, isReverse) {

  if(typeof isReverse == 'undefined') {
    isReverse = true;
  }

  var hi = arr[0],
  lo = arr[1];
  return padLeft((isReverse ? hi + lo * 0x100 : hi * 0x100 + lo).toString(16).toUpperCase(), 4, '0');

};

function padLeft(s, w, pc) {

    if (pc == undefined) {
        pc = '0';
    }

    for (var i = 0, c = w - s.length; i < c; i++) {
        s = pc + s;
    }

    return s;

};

//十六进制字符串转字节数组
function HexString2Bytes(str) {

    var pos = 0;
    var len = str.length;

    if (len % 2 != 0) {
      return null;
    }

    len /= 2;
    var arrBytes = new Array();

    for (var i = 0; i < len; i++) {
      var s = str.substr(pos, 2);
      var v = parseInt(s, 16);
      arrBytes.push(v);
      pos += 2;

    }

    return arrBytes;
  }

你可能感兴趣的:(javascript,前端,开发语言)