Search code examples
phpcrcxmodem

php calculated CRC-CCITT (XModem)


I'm trying to implement a CRC-CCITT (XModem) check in php without success. Does anyone know how to do it? I expected crc16('test') will return 0x9B06.


Solution

  • Here is a simple bit-wise calculation of the XMODEM 16-bit CRC, in C:

    #include <stdint.h>
    
    unsigned crc16xmodem_bit(unsigned crc, void const *data, size_t len) {
        if (data == NULL)
            return 0;
        while (len--) {
            crc ^= (unsigned)(*(unsigned char const *)data++) << 8;
            for (unsigned k = 0; k < 8; k++)
                crc = crc & 0x8000 ? (crc << 1) ^ 0x1021 : crc << 1;
        }
        crc &= 0xffff;
        return crc;
    }
    

    This was generated by my crcany software, which also generates byte-wise and word-wise versions for speed.

    This can be easily converted to php.