CRC-CCITT 16-bit Python Manual Calculation

前端 未结 7 1182
情深已故
情深已故 2021-02-06 10:48

Problem

I am writing code for an embedded device. A lot of solutions out there for CRC-CCITT 16-bit calculations require libraries.

Given that u

7条回答
  •  别那么骄傲
    2021-02-06 11:26

    The accepted answer above is wrong. It does not augment a zero-length input with 16 bits of 0, as given by http://srecord.sourceforge.net/crc16-ccitt.html. Luckily, it can be fixed very easily. I will only post the changes that I've made.

    def crc(str):
        crc = PRESET
        # start crc with two zero bytes
        for _ in range(2):
            crc = _update_crc(crc, 0)
        for c in str:
            crc = _update_crc(crc, ord(c))
        return crc
    
    def crcb(*i):
        crc = PRESET
        for _ in range(2):
            crc = _update_crc(crc, 0)
        for c in i:
            crc = _update_crc(crc, c)
        return crc
    

    Now, if we compare the new implementation to the expected CRC values, we get the "good_crc" values instead of "bad_crc" values.

提交回复
热议问题