计算CRC码的步骤为:
1, 预置16位寄存器为16进制FFFF(即全为1)。称此寄存器为CRC寄存器;
2, 把第一个8位数据与16位CRC寄存器的低位相异或,把结果放于CRC寄存器;
3, 检查最低位:
如果最低位为0,把寄存器内容右移一位(朝低位),用0填补最高位;
如果最低位为1,把寄存器内容右移一位(朝低位),CRC寄存器与多项式A001(1010 0000 0000 0001)进行异或;
4, 重复步骤3,直到右移8次,这样整个8位数据全部了处理;
5, 重复步骤2到步骤4,进行下一个8位数据的处理;
6, 最后得到的CRC寄存器即为CRC码;
7, 将CRC结果放入信息帧时候,将高低位交换,低位在前,并转换成4个字节的ASCII码;
例:unsigned short crc(unsigned char *crc_pointer,unsigned short data_length)
{
   unsigned short k,k0,bit_flag;
   unsigned short int_crc=0xffff;
   for (k=0;k<data_length;k++)
   {
        int_crc^=*(crc_pointer++);
        for(k0=0;k0<8;k0++)
        {
            bit_flag=int_crc&0x0001;
            int_crc>>=1;
            if (bit_flag==1)
                int_crc^=0xa001;
        }
   }
   return(int_crc);
}
如何用DELPHI实现!!!
谢谢!!!

解决方案 »

  1.   

    function   GetCrcwd(const   pData:Pointer;nLength:Integer):string;
     var
       fcs:Word;
       p:PBYTE;
       bit : Byte;
       i : integer;
    begin
              p   :=   PBYTE(PData);
              fcs   :=   $FFFF;         //   &sup3;&otilde;&Ecirc;&frac14;&raquo;&macr;          while nLength > 0 do
              begin
                fcs := (fcs xor p^);
                i := 0;
                while i <8 do
                begin
                  bit := fcs and $0001;
                  fcs :=fcs shr 1;              if bit = 1 then
                    fcs := fcs xor $A001;
                  inc(i);
                 end;
                 dec(nLength);
              end;
              Result := fcs;    
    end;
      

  2.   

    上面代码少写了一句。。
    function   GetCrcwd(const   pData:Pointer;nLength:Integer):string;
     var
       fcs:Word;
       p:PBYTE;
       bit : Byte;
       i : integer;
    begin
              p   :=   PBYTE(PData);
              fcs   :=   $FFFF;         //   &sup3;&otilde;&Ecirc;&frac14;&raquo;&macr;          while nLength > 0 do
              begin
                fcs := (fcs xor p^);
                inc(p);//上面的代码少写了这一句
                i := 0;
                while i <8 do
                begin
                  bit := fcs and $0001;
                  fcs :=fcs shr 1;              if bit = 1 then
                    fcs := fcs xor $A001;
                  inc(i);
                 end;
                 dec(nLength);
              end;
              Result := fcs;    
    end;