关于通讯协议中FCS和CRC计算

FCS和CRC 在线计算:

Document

function calCRC() {
Crctxt = document.getElementById('crcTxt');
crc = 0xffff;
xcnst = 0xa001;
Crc2Arr = Crctxt.value.match(/.{2}/g);
Crc2Int = Crc2Arr.map(x => parseInt(x, 16));
console.log(Crc2Int);
Crc2Int.forEach((i) => {
crc ^= i
for (i = 0; i < 8; i++) {
if (crc % 2 == 0) {
crc = Math.floor(crc /2);
}
else {
crc = Math.floor(crc /2);
crc ^= xcnst;
}
}
});
crc = crc.toString(16).padStart(4,'0').match(/.{2}/g)
Crctxt.value += crc[1].toUpperCase() + crc[0].toUpperCase();
console.log(crc[1] + crc[0]);
        
def CalCRC(buf):
    crc = 65535
    xcnst = 40961
    for i in buf:
        crc ^= i
        for n in range(8):
            if(crc % 2 == 0):
                crc //= 2
            else:
                crc //= 2
                crc ^= xcnst
    return pack("<h",crc)
 function calFCS() {
Fcstxt = document.getElementById('fcsTxt');
Fcs2Arr = Array.from(Fcstxt.value);
Fcs2Asc = Fcs2Arr.map((x) => x.charCodeAt(0));
Fcs = Fcs2Asc.reduce((x, y) => { return x ^ y }).toString(16).padStart(2, '0');
Fcstxt.value += Fcs + '*\\r\\n';
}
unsigned char *calFcs(unsigned char *p, unsigned char ind)
{
unsigned char fcs[1] = {*p};
for (int i = 1; i < ind; i++)
{
fcs[0] = fcs[0] ^ *(p + i);
}
static unsigned char fcsAscii[2];
fcsAscii[0] = B2H(fcs[0] / 16);
fcsAscii[1] = B2H(fcs[0] % 16);
return fcsAscii;
}