C#和C实现通过CRC-16 (Modbus)获取CRC值并校验数据(代码)
时间: 2024-03-23 22:38:51 浏览: 198
CRC16校验码(MODBUS)原理与C#源程序
以下是C#和C语言实现通过CRC-16 (Modbus)获取CRC值并校验数据的代码:
C#代码实现:
```csharp
public static ushort CalculateCRC(byte[] data)
{
ushort crc = 0xFFFF;
for (int i = 0; i < data.Length; i++)
{
crc ^= data[i];
for (int j = 0; j < 8; j++)
{
if ((crc & 0x0001) == 0x0001)
{
crc >>= 1;
crc ^= 0xA001;
}
else
{
crc >>= 1;
}
}
}
return crc;
}
public static bool VerifyCRC(byte[] data, ushort crc)
{
ushort calculatedCrc = CalculateCRC(data);
return calculatedCrc == crc;
}
```
C语言代码实现:
```c
#include <stdio.h>
unsigned short CalculateCRC(unsigned char *data, unsigned int length)
{
unsigned short crc = 0xFFFF;
for (unsigned int i = 0; i < length; i++)
{
crc ^= data[i];
for (unsigned int j = 0; j < 8; j++)
{
if ((crc & 0x0001) == 0x0001)
{
crc >>= 1;
crc ^= 0xA001;
}
else
{
crc >>= 1;
}
}
}
return crc;
}
bool VerifyCRC(unsigned char *data, unsigned int length, unsigned short crc)
{
unsigned short calculatedCrc = CalculateCRC(data, length);
return calculatedCrc == crc;
}
int main()
{
unsigned char data[] = { 0x01, 0x03, 0x00, 0x00, 0x00, 0x02 };
unsigned short crc = CalculateCRC(data, sizeof(data));
printf("CRC: 0x%X\n", crc);
unsigned char verifyData[] = { 0x01, 0x03, 0x00, 0x00, 0x00, 0x02, 0x05, 0x02 };
unsigned short verifyCrc = 0x0205;
bool result = VerifyCRC(verifyData, sizeof(verifyData), verifyCrc);
printf("Verify Result: %d\n", result);
return 0;
}
```
注意:以上代码仅为示例,具体实现需要根据实际情况进行调整。
阅读全文