#include "CRC32.h"


CCRC32::CCRC32()
{
    InitTable();
}


void CCRC32::InitTable()
{
    quint32 i;
    quint32 j;
    quint32 crc;

    for (i=0; i<256; i++)
    {

        crc = i;

        for (j=0; j<8; j++) {

            if ( crc & 0x00000001L ) crc = ( crc >> 1 ) ^ CRC_POLY_32;
            else                     crc =   crc >> 1;
        }

        mCRC32Table[i] = crc;
    }
}

quint32 CCRC32::ComputeCRC32(QByteArray Buffer)
{
    return ComputeCRC32((const unsigned char *)Buffer.data(),Buffer.size());
}

quint32 CCRC32::ComputeCRC32( const unsigned char *input_str, qulonglong num_bytes )
{
    quint32 crc;
    quint32 tmp;
    quint32 long_c;
    const unsigned char *ptr;
    qulonglong a;

    crc = CRC_START_32;
    ptr = input_str;

    if ( ptr != NULL ) for (a=0; a<num_bytes; a++) {

        long_c = 0x000000FFL & (quint32) *ptr;
        tmp    =  crc       ^ long_c;
        crc    = (crc >> 8) ^ mCRC32Table[ tmp & 0xff ];

        ptr++;
    }

    crc ^= 0xffffffffL;

    return crc & 0xffffffffL;
}

quint32 CCRC32::UpdateCRC32(quint32 crc, unsigned char c)
{
    quint32 tmp;
    quint32 long_c;

    long_c = 0x000000ffL & (quint32) c;


    tmp = crc ^ long_c;
    crc = (crc >> 8) ^ mCRC32Table[ tmp & 0xff ];



    return crc & 0xffffffffL;;
}
