unit untCRC16;
interface
uses
Windows;
/// <summary>
/// CRC校验码(从厂家提供C语言翻译而来)
/// </summary>
/// <param name="crc_ini">$00</param>
/// <param name="buf"></param>
/// <param name="len"></param>
/// <returns></returns>
function Crc16(crc_ini: Word; buf: PByte; len: LongWord): Word;
/// <summary>
/// CRC校验码(字符串)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
function Crc16str(str: string): Word;
//调用 ShowMessage(IntToHex(Crc16str('123'),4)); { = $5297}
const
CRC_TA: array[0..15] of Word = ($0000, $1021, $2042, $3063, $4084, $50a5, $60c6, $70e7,
$8108, $9129, $a14a, $b16b, $c18c, $d1ad, $e1ce, $f1ef);
implementation
function Crc16(crc_ini: Word; buf: PByte; len: LongWord): Word;
var
crc: Word;
da: Byte;
begin
crc := crc_ini;
while len <> 0 do
begin
da := Byte((crc div 256) div 16);
crc := crc shl $04;
crc := crc xor CRC_TA[da xor (buf^ div 16)];
da := (Byte(crc div 256)) div 16;
crc := crc shl $04;
crc := crc xor CRC_TA[da xor (buf^ and $0f)];
inc(buf);
len := len - 1;
end;
//Result := crc;
Result := MakeWord(hi(crc), lo(crc)); //高低位互换
end;
function Crc16str(str: string): Word;
var
arrStr: array of Byte;
i: integer;
begin
SetLength(arrStr, Length(str));
for i := Low(arrStr) to High(arrStr) do
arrStr[i] := Ord(str[i + 1]);
Result := Crc16($00, @arrStr[0], Length(arrStr));
end;
end.
原C语言版
CRC 校验 C 语言源码(ARM Cotex M3 ):
//==========================================================================
UNT16 CRC_TA[16] = {0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,
0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef};
//==========================================================================
UINT16 Crc16(UINT16 crc_ini, const UINT08 *buf, UINT32 len) {
UINT16 crc = crc_ini;
UINT08 da;
while (len-- != 0) {
da = ((UINT08)(crc / 256)) / 16;
crc <<= 0x04;
crc ^= CRC_TA[da ^ (*buf / 16)];
da = ((UINT08)(crc / 256)) / 16;
crc <<= 0x04;
crc ^= CRC_TA[da ^ (*buf & 0x0f)];
buf++;
}
return(crc);
}