javascript实现CRC校验
2022/06/23    
    //获得CRC校验码的方法
let getCrcCode = function(binaryOrgString,binaryCrcJiaoyan){
    // binaryOrgString 被校验二进制串;binaryCrcJiaoyan 多项式对应二进制串;crcCode 返回校验码
    let crcCode = '', binaryTemp = '0';
    binaryOrgString = binaryOrgString + '' + binaryTemp.repeat(binaryCrcJiaoyan.length-1);//需要再原来的二进制串后补上和校验多项式长度减1个零(因为校验码的位数比生成多项式的位数少1)
    let getCrcCodeDeep = function(binaryOrgString,binaryCrcJiaoyan,yushu){
        //递归获取二进制
        if(typeof(yushu)==='undefined'){
            yushu = '';
        }
        let yushuCurr = yushu + '' + binaryOrgString.substr(0,binaryCrcJiaoyan.length - yushu.length);
        if(yushuCurr.length < binaryCrcJiaoyan.length){
            //当前余数小于多项式校验位长度,即不够除的,则为最后的余数返回
            crcCode = yushuCurr;
            return;
        }
        binaryOrgString = binaryOrgString.substr(binaryCrcJiaoyan.length - yushu.length);
        yushuNext = parseInt(yushuCurr,2) ^ parseInt(binaryCrcJiaoyan,2);
        getCrcCodeDeep(binaryOrgString,binaryCrcJiaoyan,yushuNext.toString(2));
    }
    getCrcCodeDeep(binaryOrgString,binaryCrcJiaoyan);
    return crcCode;
}

let str = 'AA BB CC 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 32 30 30 30 30 30 30 30 30 30 30 30 34 30 30 30 30 31 30 30 30 30 31 30 30 34 30 30 30 30 34 30 31 30 31 35 30 30 32 32 30 36 32 33 30 37 35 32 34 33 32 32 30 36 32 33 30 37 35 32 35 38';
let binaryArr = str.split(' ').map(function(val){
    var binaryCurr = parseInt('0x'+val,16).toString(2);
    var binaryTemp = '0';
    binaryCurr = binaryTemp.repeat(8-binaryCurr.length) + binaryCurr;
    return binaryCurr;
});
// arrs = str.split(' ').map(function(val){
//     return parseInt('0x'+val,16);
// });
// console.log(JSON.stringify(Buffer.from(arrs)));
//多项式计算 CRC8校验(x8+x2+x+1)
let binaryCrcJiaoyan = '100000111';

//获得校验码(CRC码)
let crcCode = getCrcCode(binaryArr.join(''), binaryCrcJiaoyan);
//将校验码放在原来二进制后面,得到最终要传输的数据
let binaryStringLast = binaryArr.join('')+crcCode;

//检验传输数据是否正确。用收到的数据,进行获取校验码(即收到的数据除以约定好的多项式,如余数为0则传输正确,否则错误要求重传);
console.log(getCrcCode(binaryStringLast, binaryCrcJiaoyan));

let str1 = 'AA BB CC 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 32 30 30 30 30 30 30 30 30 30 30 30 34 30 30 30 30 31 30 30 30 30 31 30 30 34 30 30 30 30 34 30 31 30 31 35 30 30 32 32 30 36 32 33 30 37 35 32 34 33 32 32 30 36 32 33 30 37 35 32 35 38 8D';
let binaryArr1 = str1.split(' ').map(function(val){
    var binaryCurr = parseInt('0x'+val,16).toString(2);
    var binaryTemp = '0';
    binaryCurr = binaryTemp.repeat(8-binaryCurr.length) + binaryCurr;
    return binaryCurr;
});
console.log(getCrcCode(binaryArr1.join(''),binaryCrcJiaoyan));