Js CRC16/CCITT

class CRC16Util {  

  
    static initial(c) { 
		let POLYNOMIAL = 0x8408;
        let crc = 0;  
        for (let j = 0; j < 8; j++) {  
            if (((crc ^ c) & 1) == 1) {  
                crc = ((crc >> 1) ^ POLYNOMIAL);  
            } else {  
                crc = (crc >> 1);  
            }  
            c = c >> 1;  
        }  
        return crc;  
    }  
    static update_crc(crc, c) {  
		let tab = new Array(256).fill(0);  
	    for (let i = 0; i < 256; i++) {  
            tab[i] = this.initial(i);  
        }  
		
        let cc = (0xff & c);  
        let tmp = (crc ^ cc);  
		
        return (crc >> 8) ^ tab[tmp & 0xff];  
    }  
    static swab(n) {  
        return (((n & 0xFF00) >> 8) + ((n & 0xFF) << 8));  
    }  
    static crc(str) {  
        return this.crcb(str.split('').map(c => c.charCodeAt(0)));  
    }  
    static crcb(...i) {  
        let crc = 0;  
        for (let c of i) {  
            crc = this.update_crc(crc, c);  
        }  
        return this.swab(crc);  
    }  
    static highLowSwap(crc) {  
        crc = ((crc & 0xFF00) >> 8) | ((crc & 0x00FF) << 8);  
        return crc.toString(16).padStart(4, '0');  
    }  
    static crc16CcittKermitHighLowSwap(...i) {  
        let crc = this.PRESET;  
        for (let c of i) {  
            crc = this.update_crc(crc, c);  
        }  
        return this.highLowSwap(this.swab(crc));  
    }  
}   
const crcMsgB = [0x1A, 0x3B, 0x4C, 0x5D]; 
// d6a1
console.log(CRC16Util.crc16CcittKermitHighLowSwap(...crcMsgB));
// a1d6
console.log(parseInt(CRC16Util.crcb(...crcMsgB)).toString(16).padStart(4, '0'));

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