<< Click to Display Table of Contents >> Navigation: Multi-Protocol MasterOPC Server > Lua 5.1 Reference Manual > Examples and Other Useful Things > Examples of Calculations of Checksums > CRC-CCITT |
CRC-CCITT is the "Cyclic redundancy check" checksum (Wikipedia:Cyclic redundancy check). Different variations of this method of checksums are the most common in industrial protocols. Below are two versions of such a checksum - CRC-CCITT Modbus and CRC-CCITT XModem.
The CRC-CCITT Modbus checksum
function ModbusCRC(ArrayByte)
local crc=0xFFFF;
for i=1,table.maxn(ArrayByte),1 do
crc=bit.BitXor(crc,ArrayByte[i]);
for j=0,7,1 do
if bit.BitAnd(crc,0x1)~=0 then
crc=bit.BitRshift(crc,1);
crc=bit.BitXor(crc,0xA001);
else
crc=bit.BitRshift(crc,1);
end;
end;
end;
--change the bytes swapped
byte1=bit.BitAnd( bit.BitLshift(crc,8),0xFFFF);
byte2=bit.BitRshift(crc,8);
return bit.BitOr(byte1,byte2 );
end;
Example of the use
local Array={0x01,0x03,0x00,0x00,0x00,0x01};
local CRC=ModbusCRC(Array);
--CRC=0x840A
The CRC-CCITT XModem checksum
function XModemCRC(ArrayByte)
len=table.maxn( ArrayByte);
local crc = 0x0;
for j=1,len,1 do
local z=bit.BitAnd(bit.BitLshift(ArrayByte[j],8),0xFFFF);
crc = bit.BitXor(crc,z);
for i = 0, 7, 1 do
if bit.BitAnd(crc,0x8000)>0 then
local k=bit.BitAnd(bit.BitLshift(crc,1),0xFFFF);
crc=bit.BitXor(k,0x1021);
else
crc=bit.BitAnd(bit.BitLshift(crc,1),0xFFFF);
end;
end;
end;
return crc;
end;
Example of the use
local Array={0x3F,0x02,0x01,0x23,0x45,0x67};
local CRC=XModemCRC(Array);
--CRC=E956