public byte[] GetCRC16(string content)
{
byte[] bytes = Encoding.UTF8.GetBytes(content);
byte[] crc16 = CRC16(bytes);
return crc16;
}
public byte[] CRC16(byte[] bytes)
{
int length = bytes.Length;
if (length > 0)
{
ushort crc = 0xFFFF;
for (int i = 0; i < length; i++)
{
crc = (ushort)(crc ^ bytes[i]);
for (int j = 0; j < 8; j++)
{
if ((crc & 1) != 0)
{
crc = (ushort)((crc >> 1) ^ 0xA001);
}
else
{
crc = (ushort)(crc >> 1);
}
}
}
byte high_order = (byte)((crc & 0xFF00) >> 8);
byte Low_order = (byte)(crc & 0x00FF);
return new byte[] { high_order, Low_order };
}
return new byte[] { 0x00, 0x00 };
}
C# CRC16 MODBUS 校验
最新推荐文章于 2025-10-23 18:14:01 发布
本文介绍了一种CRC16校验码生成算法的实现方法,通过将字符串转换为字节序列,并使用CRC16算法计算校验码,最终返回高字节和低字节组成的字节数组。该算法在数据通信和文件传输中用于检测错误。

1万+





