t3486784401 发表于 2011-7-26 08:43:39

[C++源码]CRC计算类

查表法计算字节流、文件的CRC32值,使用了C++类封装;

现贴出来与大家分享下:)

点击此处下载 ourdev_661097ZILPGF.rar(文件大小:1K) (原文件名:CRC32.rar)

//-------------------------------------- 华丽的分割线 --------------------------------------------

// CRC32.h: interface for the CRC32 class.
//
//////////////////////////////////////////////////////////////////////

#pragma once

class CRC32
{
public:
    CRC32();
    ~CRC32();

// CRC32表格
private:
    unsigned __int32 m_crc32Table;

// 对外接口
public:
    unsigned __int32 GetCRC32(void *pData, long dwLen);
    unsigned __int32 GetCRC32(LPCTSTR szFileName);
};



//-------------------------------------- 飘逸的分割线 --------------------------------------------

// CRC32.cpp: implementation of the CRC32 class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "CRC32.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CRC32::CRC32()
{
    // 初始化CRC32表格
    int i,j;
    unsigned __int32 crc;

    for(i=0;i<256;i++)
    {
      crc=i;
      for(j=0;j<8;j++)
      {
            if(crc &1)
                crc= (crc>>1) ^ 0xEDB88320;
            else
                crc>>=1;
      }
      m_crc32Table=crc;
    }
}

CRC32::~CRC32()
{

}

//////////////////////////////////////////////////////////////////////
// Interface
//////////////////////////////////////////////////////////////////////

/* 计算长度为 dwLen 字节 pData 字节串的CRC32值 */
unsigned __int32 CRC32::GetCRC32(void *pData, long dwLen)
{
    unsigned __int32 crc= 0xFFFFFFFF;
    unsigned __int8*buffer= (unsigned __int8*)pData;

    for(long i=0;i<dwLen;i++)
    {
      crc= (crc>>8) ^ m_crc32Table[ (crc&0xFF)^buffer ];
    }

    return crc^0xFFFFFFFF;
}

/* 计算路径名为 szFileName 文件的CRC32值 */
unsigned __int32 CRC32::GetCRC32(LPCTSTR szFileName)
{
    unsigned __int32 crc= 0xFFFFFFFF;
    unsigned __int32 i,nRead;
    unsigned __int8 buffer;

    CFile file;
    if(FALSE==file.Open(szFileName, CFile::modeRead|CFile::typeBinary))
    {
      AfxMessageBox(_T("文件打开失败"));
      return 0x00000000;
    }

    nRead= file.Read(buffer,1024);
    while(nRead>0)
    {
      for(i=0; i<nRead; i++)
      {
            crc= (crc>>8) ^ m_crc32Table[ (crc&0xFF)^buffer ];
      }
      nRead= file.Read(buffer,1024);
    }
    file.Close();

    return crc^0xFFFFFFFF;
}

yulri 发表于 2011-7-27 19:12:09

下载不了

ITOP 发表于 2011-7-27 20:09:27

研究下!
页: [1]
查看完整版本: [C++源码]CRC计算类