//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