CRC_CCITT js版的计算函数

CRC_CCITT,特征多项式:X16+X12+X5+1,即多项式系数为 0x1021,初始值为全 0,对于单个字节来说最高位先计算需要取反直接输出。


function calculateCRC_CCITT(buffer) {
    const POLYNOMIAL = 0x1021;
    let crc = 0x0000; // Initial value set to all 0s for this specific case

    for (let i = 0; i < buffer.length; i++) {
        crc ^= (buffer[i] << 8); // XOR the current byte with the CRC value, shifted left by 8 bits
        for (let j = 8; j > 0; j--) {
            if (crc & 0x8000) { // Check highest bit of crc
                crc = ((crc << 1) & 0xFFFF) ^ POLYNOMIAL;
            } else {
                crc = (crc << 1) & 0xFFFF;
            }
        }
    }
    return crc & 0xFFFF; // Ensure that the final result fits within 16 bits
}

const TYPES = new Uint8Array([0x07]);
const LENS = new Uint8Array([0x01]);
const ADDRESS = new Uint8Array([0x00, 0x00]); // Start address
const DATAS = new Uint8Array([0x01]); // Number of bytes to read

// Concatenate all parts except HEAD1 which is not included in CRC calculation
const crcData = new Uint8Array([
    ...TYPES,
    ...LENS,
    ...ADDRESS,
    ...DATAS
]);

const crcResult = calculateCRC_CCITT(crcData);
console.log('CRC-CCITT:', crcResult.toString(16).toUpperCase().padStart(4, '0'));

posted @ 2024-07-12 14:21  星小梦  阅读(11)  评论(0编辑  收藏  举报