Search code examples
c#hashcrc

CRC_82_Darc function in C#


I need to calculate the CRC_82_Darc hash in C#. Is there any preexisting Lib for this or did someone already write a function ? I could not find anything on Google.


Solution

  • Here is a simple bit-wise implementation in C:

    // CRC-82/DARC Calculation
    // Placed into the public domain by Mark Adler, 17 June 2017.
    
    // CRC definition:
    // width=82 poly=0x0308c0111011401440411 init=0 refin=true refout=true xorout=0
    // check=0x09ea83f625023801fd612 name="CRC-82/DARC"
    
    #include <stddef.h>
    #include <stdint.h>
    
    #define POLYHIGH 0x22080
    #define POLYLOW 0x8a00a2022200c430
    
    // Update crc[0..1] with the CRC-82/DARC of the len bytes at buf. If buf is
    // NULL, then initialize crc[0..1] with the CRC-82/DARC of an empty message.
    // The low 64 bits of the CRC are in crc[0], and the high 18 bits of the CRC
    // are in the low 18 bits of crc[1]. The remaining bits of crc[1] are always
    // zero.
    void crc82darc(uint64_t *crc, void const *buf, size_t len) {
        if (buf == NULL) {
            crc[0] = crc[1] = 0;
            return;
        }
        uint64_t cl = crc[0], ch = crc[1] & 0x3ffff;
        for (size_t i = 0; i < len; i++) {
            cl ^= ((unsigned char const *)buf)[i];
            for (int k = 0; k < 8; k++) {
                uint64_t low = cl & 1;
                cl = (cl >> 1) | (ch << 63);
                ch >>= 1;
                if (low) {
                    cl ^= POLYLOW;
                    ch ^= POLYHIGH;
                }
            }
        }
        crc[0] = cl;
        crc[1] = ch;
    }
    
    #ifdef TEST
    
    #include <stdio.h>
    
    int main(void)
    {
        uint64_t crc[2];
    
        crc82darc(crc, NULL, 0);    // initialize crc
        crc82darc(crc, "123456789", 9);
        printf("0x%05llx%016llx\n", crc[1], crc[0]);
        return 0;
    }
    
    #endif