CRC16算法函数

//Delphi版
function CRC16(P:PChar;Count:Cardinal):WORD; //P 字符串 Count串长
  var 
    I,CRC:WORD; 
    CH:Byte; 
  begin 
    CRC:=$FFFF; 
    for i:=1 to Count do 
      begin 
        CRC:=CRC xor Byte(p^); 
        p:=p+1; 
        for ch:=0 to 7 do 
          begin 
            if (crc and $01)=1 then 
              begin 
                crc:=crc shr 1; 
                crc:=crc xor $a001; 
              end 
            else 
              begin 
                crc:=crc shr 1; 
              end; 
          end; 
      end; 
    CRC16:=CRC; 
  end; 

'VB6版 Data数据 Offset起始位置 Length待计算数据长度
Public Function CRC16(Data() As Byte, Optional ByVal Offset As Integer = 0, Optional ByVal Length As Integer = 0) As Byte() 
  Dim CRC16Lo As Byte, CRC16Hi As Byte      'CRC寄存器 
  Dim CL As Byte, CH As Byte                '多项式码&HA001 
  Dim SaveHi As Byte, SaveLo As Byte 
  Dim I As Integer 
  Dim Flag As Integer 
  Dim ReturnData(1) As Byte 
  CRC16Lo = &HFF 
  CRC16Hi = &HFF 
  CL = &H1 
  CH = &HA0 
  Length = IIf(Length < 1, UBound(Data) - Offset, Length - 1)   'Update 2007-03-15 
  For I = Offset To Offset + Length 
    CRC16Lo = CRC16Lo Xor Data(I) '每一个数据与CRC寄存器进行异或 
    For Flag = 0 To 7 
      SaveHi = CRC16Hi 
      SaveLo = CRC16Lo 
      CRC16Hi = CRC16Hi / 2            '高位右移一位 
      CRC16Lo = CRC16Lo / 2            '低位右移一位 
      If ((SaveHi And &H1) = &H1) Then '如果高位字节最后一位为1 
        CRC16Lo = CRC16Lo Or &H80      '则低位字节右移后前面补1 
      End If                           '否则自动补0 
      If ((SaveLo And &H1) = &H1) Then '如果LSB为1,则与多项式码进行异或 
        CRC16Hi = CRC16Hi Xor CH 
        CRC16Lo = CRC16Lo Xor CL 
      End If 
    Next 
  Next 
  ReturnData(0) = CRC16Lo              'CRC低位 
  ReturnData(1) = CRC16Hi              'CRC高位 
  CRC16 = ReturnData 
End Function 

//C语言版 buf数据 length数据长度
unsigned int CRC16(unsigned char *buf,unsigned char length)//CRC16计算
{
  unsigned char i;
  unsigned int crc=0xFFFF;
  while(length--)
    for(crc^=*(buf++),i=0;i<8;i++)
      crc=(crc&0x0001)?(crc>>1)^0xA001:crc>>1;
  return crc;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值