CRC-32 (Ethernet)

par skywodd | | Langue : C++ | Licence : GPLv3

Description :

CRC-32 (Ethernet)

  • CRC 32 bits

  • Polynôme 0x04C11DB7

  • Valeur initiale 0xFFFFFFFF

  • Inversion de l'entrée et de la sortie

  • XOR final 0xFFFFFFFF

Code source :

Voir le code source brut | Télécharger crc32_ethernet.c | Télécharger crc32_ethernet.c.zip

#include <stdint.h>


uint32_t bit_reflect(uint32_t data, unsigned char nbits) {
    uint32_t output = 0;
    for (unsigned char i = 0; i < nbits; ++i) {
        if (data & 1) 
            output |= 1 << ((nbits - 1) - i);
        data >>= 1;
    }
    return output;
}


uint32_t crc32_ethernet(char* data, unsigned int data_len) {
    uint32_t crc = 0xFFFFFFFF;

    if (data_len == 0)
        return 0;

    for (unsigned int i = 0; i < data_len; ++i) {
        uint32_t dbyte = bit_reflect(data[i], 8);
        crc ^= dbyte << 24;
        
        for (unsigned char j = 0; j < 8; ++j) {
            uint32_t mix = crc & 0x80000000;
            crc = (crc << 1);
            if (mix)
                crc = crc ^ 0x04C11DB7;
        }
    }

    return bit_reflect(crc, 32) ^ 0xFFFFFFFF;
}