Delphi CRC16校验码

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);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值