本帖最后由 dgxum 于 2012-11-16 14:47:31 编辑

解决方案 »

  1.   

    unit unCRC16;interfacefunction CalCRC16(AData:array of Byte; AStart,AEnd:Integer): Word;implementationfunction CalCRC16(AData:array of Byte; AStart,AEnd:Integer): Word;
    const
      GENP = $A001;
      
    var
      crc:Word;
      i:Integer;
      tmp:Byte;
      
    procedure CalOneByte(AByte:Byte);
    var
      j:Integer;
    begin
      crc:=crc xor AByte;
      for j := 0 to 7 do
      begin
        tmp:=crc and 1;
        crc:=crc shr 1;
        crc:= crc and $7FFF;
        if tmp = 1 then
          crc:= crc xor GENP;
        crc:=crc and $FFFF;
      end;  
    end;begin
      crc:=$FFFF;
      for i := AStart to AEnd do
        CalOneByte(AData[i]);
      Result:=crc;
    end;  end.
      

  2.   

    哥,好像有点不对:
    procedure TMainFrm.Button1Click(Sender: TObject);
    var  d:array [0..7] of Byte;
    begin
      d[0]:=1;
      d[1]:=2;
      d[2]:=3;
      d[3]:=4;
      d[4]:=5;
      d[5]:=6;
      d[6]:=7;
      d[7]:=8;
      edit1.Text:=IntToHex(CalCRC16(d,0,7),2);
    end;
    这样算出来的是:CFB0
    原来的C算法出来的应该是:C4F0
    怎么办呀?
      

  3.   

    好了,可以了,是CRC的初始值的问题,改成0即正常。
      

  4.   

    唉,来晚了function GetCRC(PBuffer: array of Byte; Length: Word): Word;
    var
      i, j: integer;
      tem: array[0..1] of Byte;
      lsb0, lsb1: Byte;
    begin
      tem[0] := 0;                                    // 初始化CRC寄存器为0
      tem[1] := 0;
      for i := 0 to Length - 1 do
      begin
        tem[1] := PBuffer[i];               // 输入数据与CRC寄存器低字节异或
        for j := 0 to 7 do
        begin
          lsb0   := tem[0] and 1;                  // 取高字节的最低位
          tem[0] := tem[0] shr 1;
          lsb1   := tem[1] and 1;                  // 取低字节的最低位
          tem[1] := tem[1] shr 1;
          if (lsb0 <> 0) then
            tem[1] := tem[1] or $80;
          if (lsb1 <> 0) then                  // 最低位为1,CRC寄存器与0xa001异或
          begin
            tem[0] := $a0;
            tem[1] := $01;
          end;
        end;
      end;
      Result := tem[0] *256 + tem[1];
    end;