- Код: Выделить всё
unsigned getKS(char *uk, unsigned kol)
{
unsigned crc;
char kk;
crc=0xFFFF;
for( ; kol; --kol) {
crc ^= *uk++ ;
for(kk=8; kk; --kk) {
if(crc & 1) { crc >>=1; crc ^=0xA001; }
else crc >>=1;
}
}
return crc;
}
Это на VB
- Код: Выделить всё
Public Function КонтрольнаяСумма(ByVal Buffer As String) As String
Dim c As Variant, k As Long, k1 As Long
Dim crc(1 To 16) As Byte, AOO1(1 To 16) As Byte
Dim Ves(1 To 16) As Byte
k = 1
For i = 1 To 16
crc(i) = 1
AOO1(i) = 0
Ves(i) = CByte(k)
If i = 8 Then
k = 1
Else
k = k * 2
End If
Next i
AOO1(1) = 1
AOO1(16) = 1
AOO1(14) = 1
While Buffer <> ""
c = Mid(Buffer, 1, 1)
'Xor c байтом буфера
For i = 1 To 8
crc(i) = crc(i) Xor Sgn(Asc(c) And Ves(i))
Next i
For i = 1 To 8
‘запоминаем 1 бит
k = crc(1)
‘Сдвиг в право
For j = 1 To 15
crc(j) = crc(j + 1)
Next j
crc(16) = 0
If k = 1 Then
'Õ&r c A001
For j = 1 To 16
crc(j) = crc(j) Xor AOO1(j)
Next j
End If
Next i
Buffer = Mid(Buffer, 2)
Wend
'Cчитаем вес байтов
k = 0
k1 = 0
For i = 1 To 16
If i <= 8 Then
k = k + Ves(i) * crc(i)
Else
k1 = k1 + Ves(i) * crc(i)
End If
Next i
КонтрольнаяСумма = Chr(k1) + Chr(k)
End Function
Public Function КонтрольнаяСумма1(ByVal Buffer As String) As String
Dim c As Variant, k As Long, k1 As Long
Dim crc(1 To 2) As Byte
crc(1) = 255
crc(2) = 255
While Buffer <> ""
c = Mid(Buffer, 1, 1)
'Xor c байтом буфера
crc(1) = crc(1) Xor Asc(c)
For i = 1 To 8
'запоминаем 1 бит
k = crc(1) And 1
‘Сдвиг в право
crc(1) = crc(1) \ 2 + 128 * (crc(2) And 1)
crc(2) = crc(2) \ 2
If k = 1 Then
'xor c A001
crc(1) = crc(1) Xor 1
crc(2) = crc(2) Xor CByte("&HA0")
End If
Next i
Buffer = Mid(Buffer, 2)
Wend
КонтрольнаяСумма1 = Chr(crc(2)) + Chr(crc(1))
End Function
Public Function КонтрольнаяСумма2(ByVal Buffer As String) As String
Dim c As Variant
Dim crc As Long, i As Long
crc = CLng("&HFFFF")
While Buffer <> ""
c = Mid(Buffer, 1, 1)
'Xor c байтом буфера
crc = crc Xor Asc(c)
For i = 1 To 8
If (crc And 1) = 1 Then
‘Сдвиг в право
crc = crc \ 2
'Xor c A001
crc = crc Xor CLng("&HA001")
Else
‘Сдвиг в право
crc = crc \ 2
End If
Next i
Buffer = Mid(Buffer, 2)
Wend
КонтрольнаяСумма2 = Chr(crc \ 256) + Chr(crc And 255)
End Function