src/network/crc32.cc

00001 #include "crc32.h"
00002 
00003 CRC32::CRC32()
00004 {
00005 }
00006 
00007 void CRC32::Init(unsigned long pol)
00008 {
00009         if (pol == 0x00000000)
00010         {
00011                 // This is the official polynomial used by CRC-32
00012                 // in PKZip, WinZip and Ethernet.
00013                 pol = 0x04c11db7;
00014         }
00015     for(int i = 0; i <= 0xFF; i++)
00016         {
00017                 crc32Table[i] = Reflect(i, 8) << 24;
00018                 for (int j = 0; j < 8; j++)
00019                 {
00020                         crc32Table[i] = (crc32Table[i] << 1) ^ (crc32Table[i] & (1 << 31) ? pol : 0);
00021                 }
00022                 crc32Table[i] = Reflect(crc32Table[i], 32);
00023         } 
00024         
00025 }
00026 
00027 unsigned long CRC32::Reflect(unsigned long r, char c)
00028 {
00029         unsigned long value(0);
00030 
00031         // Swap bit 0 for bit 7
00032         // bit 1 for bit 6, etc.
00033         for(int i = 1; i < (c + 1); i++)
00034         {
00035                 if(r & 1)
00036                 {
00037                         value |= 1 << (c - i);
00038                 }
00039                 r >>= 1;
00040         }
00041         return value; 
00042 }
00043 
00044 unsigned long CRC32::GetCRC(char *rawData, int len)
00045 {
00046         // Once the lookup table has been filled in by the two functions above,
00047         // this function creates all CRCs using only the lookup table.
00048         
00049         // Be sure to use unsigned variables,
00050         // because negative values introduce high bits
00051         // where zero bits are required.
00052         
00053         // Start out with all bits set high.
00054         unsigned long  CRC(0xffffffff);
00055         unsigned char *buffer;
00056 
00057         buffer = (unsigned char *)rawData;
00058         // Perform the algorithm on each character
00059         // in the string, using the lookup table values.
00060         while (len--)
00061         {
00062                 CRC = (CRC >> 8) ^ crc32Table[(CRC & 0xFF) ^ *buffer++];
00063         }
00064         
00065         // Exclusive OR the result with the beginning value.
00066         return (CRC ^ 0xffffffff);
00067 }
00068 

Generated on Mon Dec 3 04:30:13 2007 for lo-testserver by  doxygen 1.3.9.1