请使用以下代码:
// Compute the MODBUS RTU CRCprivate static int ModRTU_CRC(byte[] buf, int len){ int crc = 0xFFFF; for (int pos = 0; pos < len; pos++) { crc ^= (int)buf[pos] & 0xFF; // XOR byte into least sig. byte of crc for (int i = 8; i != 0; i--) { // Loop over each bit if ((crc & 0x0001) != 0) { // If the LSB is set crc >>= 1; // Shift right and XOR 0xA001 crc ^= 0xA001; } else // Else LSB is not set crc >>= 1; // Just shift right } }// Note, this number has low and high bytes swapped, so use it accordingly (or swap bytes)return crc; }但是,您可能必须反转返回的CRC才能获得正确的字节序。我什至在这里测试过:
http://ideone.com/PrBXVh
使用Windows计算器或其他工具,您可以看到第一个结果(来自上述函数调用)给出了预期值(尽管取反)。



