Crc-16/modbus algorithm:
The CRC is calculated using only 8 data bits, starting bit and stop bit, if parity bit also includes parity bit, do not participate in CRC calculation.
The CRC is calculated by:
1. Load a 16-bit register with a value of 0XFFFF, which is the CRC register.
2, the first 8-bit binary data (that is, the first byte of the communication information frame) and the 16-bit CRC register is different or, the result is still stored in the CRC register.
3, the CRC register the contents of the right one bit, with 0 to fill the highest bit, and detect the shift out of the bit is 0 or 1.
4. If the move-out bit is zero, repeat the third step (move right one bit again), or if the 1,CRC register is different from the 0xa001.
5, repeat steps 3 and 4, until the right shift 8 times, so that the entire 8-bit data are all processed.
6, repeat steps 2 and 5, the processing of the next byte of the communication information frame.
7, the communication information frame all bytes according to the above steps, the resulting 16-bit CRC register high and low byte to Exchange
8, the final CRC register content is: CRC check code.
C # code:
void ModBusCRC16(ref byte[] cmd, int len){ ushort i, j, tmp, CRC16; CRC16 = 0xFFFF; //CRC寄存器初始值 for (i = 0; i < len; i++) { CRC16 ^= cmd[i]; for (j = 0; j < 8; j++) { tmp = (ushort)(CRC16 & 0x0001); CRC16 >>= 1; if (tmp == 1) { CRC16 ^= 0xA001; //异或多项式 } } } cmd[i++] = (byte) (CRC16 & 0x00FF); cmd[i++] = (byte) ((CRC16 & 0xFF00)>>8);}
Crc-16/modbus algorithm