CRC校验? (40分)

  • 主题发起人 主题发起人 luckchen8256
  • 开始时间 开始时间
L

luckchen8256

Unregistered / Unconfirmed
GUEST, unregistred user!
请各位大虾帮忙解释一下这个CRC校验程序,并帮忙改写成Dephi!
谢谢!
[red]m_CRC.cpp:[/red]
#include "stdafx.h"
#include "m_Crc.h"
WORD CRC(char *s,int len)
{
WORD acc = 0;
int i;
while (len--)
{
acc = acc ^ (*s++ << 8);
for (i=0;i<8;i++)
if (acc & 0x8000)
acc = (acc << 1) ^ 0x1021;
else
acc <<= 1;
}
acc = (acc<<8) | (acc>>8);
return acc;
}

[red]m_CRC.h:[/red]
#ifndef __PROTOCOL_H_
#define __PROTOCOL_H_
WORD CRC(char *s, int l);
#endif

[red]stdafx.h[/red]
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#if !defined(AFX_STDAFX_H__E8E613E9_0A8C_11D6_8F39_BD6DA280E9C0__INCLUDED_)
#define AFX_STDAFX_H__E8E613E9_0A8C_11D6_8F39_BD6DA280E9C0__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers
#include <afxwin.h> // MFC core and standard components
#include <afxext.h> // MFC extensions
#include <afxdisp.h> // MFC Automation classes
#include <afxdtctl.h> // MFC support for Internet Explorer 4 Common Controls
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include <afxcmn.h> // MFC support for Windows Common Controls
#endif // _AFX_NO_AFXCMN_SUPPORT
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_STDAFX_H__E8E613E9_0A8C_11D6_8F39_BD6DA280E9C0__INCLUDED_)
 
function CRC(s:string;len:integer):integer;
var
acc,i,j:integer;
begin
acc:=0;j:=0;
while len<>0 do begin
dec(len);
inc(j);
acc:= acc xor (ord(s[j]) shl 8);
for i:=0 to 7 do
if acc and 32768=0
then acc:=(acc shl 1) xor 4129
else acc:=acc shl 1
end;
acc:=(acc shl 8) or (acc shr 8);
result:=acc;
end;
 
是做CRC校验吧,我给你一段代码,是我编程用到的,函数GenerateCRC调用结果,返回一个CRC码.
type
iArray = Record
aArray :array[1..1024] of Byte;
aLen :Integer;
end;

function GenerateCRC(var aPackage:iArray):Word;
var
crc:Word;
ia,ib,ie,I,iCount:Integer;
caTemp:iArray;
begin
crc:=0;
ia:=0;
ib:=0;
for I:=1 to aPackage.aLen do
caTemp.aArray:=aPackage.aArray;
ie:=caTemp.aArray[1];
crc:=crc xor (ie shl 8);
crc:=crc xor caTemp.aArray[2];
iCount:=aPackage.aLen;
for I:=1 to (aPackage.aLen-2)*8 do
begin
while iCount>2 do
begin
if (caTemp.aArray[iCount] and 128)<>0 then
ia:=1
else
ia:=0;
caTemp.aArray[iCount]:=caTemp.aArray[iCount] shl 1;
if ib=1 then
caTemp.aArray[iCount]:=caTemp.aArray[iCount]+1;
ib:=ia;
iCount:=iCount-1;
end;
if (crc and 32768)<>0 then
begin
crc:=crc shl 1;
if ia=1 then
crc:=crc+1;
crc:=crc xor 4129;
end
else begin
crc:=crc shl 1;
if ia=1 then
crc:=crc+1;
end;
iCount:=aPackage.aLen;
end;
Result:=crc;
end;
不必看懂,直接调用就可以了!
 
多人接受答案了。
 
后退
顶部