CRC-CCITT 16-bit Python Manual Calculation

前端 未结 7 1184
情深已故
情深已故 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:27

    Here is a C version that you can translate to Python:

    #define POLY 0x1021
    
    /* CRC-16 XMODEM: polynomial 0x1021, init = 0, xorout = 0, no reflection */
    unsigned crc16x(unsigned crc, unsigned char *buf, size_t len)
    {
        while (len--) {
            crc ^= *buf++ << 8;
            crc = crc & 0x8000 ? (crc << 1) ^ POLY : crc << 1;
            crc = crc & 0x8000 ? (crc << 1) ^ POLY : crc << 1;
            crc = crc & 0x8000 ? (crc << 1) ^ POLY : crc << 1;
            crc = crc & 0x8000 ? (crc << 1) ^ POLY : crc << 1;
            crc = crc & 0x8000 ? (crc << 1) ^ POLY : crc << 1;
            crc = crc & 0x8000 ? (crc << 1) ^ POLY : crc << 1;
            crc = crc & 0x8000 ? (crc << 1) ^ POLY : crc << 1;
            crc = crc & 0x8000 ? (crc << 1) ^ POLY : crc << 1;
        }
        return crc & 0xffff;
    }
    

    crc is initialized to zero.

    0 讨论(0)
提交回复
热议问题