c#crc多项式0x8005,初始值为FFFF,结果异或0x000,输入反转,输入反转。写出c#代码
时间: 2025-02-02 12:12:14 浏览: 66
好的,我来为您编写一个C#代码,实现CRC-16校验(使用多项式0x8005,初始值0xFFFF,结果异或0x0000,输入和输出都反转)。代码如下:
```csharp
using System;
class CRC16
{
private const ushort POLYNOMIAL = 0x8005;
private const ushort INITIAL_VALUE = 0xFFFF;
private const ushort FINAL_XOR_VALUE = 0x0000;
public static ushort CalculateCRC(byte[] bytes)
{
ushort crc = INITIAL_VALUE;
int byteLen = bytes.Length;
for (int i = 0; i < byteLen; i++)
{
crc ^= (ushort)(bytes[i] << 8);
for (int j = 0; j < 8; j++)
{
if ((crc & 0x8000) != 0)
crc = (ushort)((crc << 1) ^ POLYNOMIAL);
else
crc <<= 1;
}
}
return (ushort)(crc ^ FINAL_XOR_VALUE);
}
public static ushort CalculateCRCWithBitReversal(byte[] bytes)
{
ushort crc = INITIAL_VALUE;
int byteLen = bytes.Length;
for (int i = 0; i < byteLen; i++)
{
byte curByte = (byte)((ReverseBits(bytes[i]) >> 8) & 0xFF);
crc ^= (ushort)(curByte << 8);
for (int j = 0; j < 8; j++)
{
if ((crc & 0x8000) != 0)
crc = (ushort)((crc << 1) ^ POLYNOMIAL);
else
crc <<= 1;
}
}
crc = ReverseBits(crc);
return (ushort)(crc ^ FINAL_XOR_VALUE);
}
private static ushort ReverseBits(ushort input)
{
ushort reversed = 0;
for (int i = 0; i < 16; i++)
{
reversed <<= 1;
reversed |= (ushort)(input & 1);
input >>= 1;
}
return reversed;
}
static void Main(string[] args)
{
byte[] data = { 0x01, 0x02, 0x03, 0x04 };
ushort crc = CalculateCRC(data);
Console.WriteLine($"CRC without bit reversal: 0x{crc:X4}");
ushort crcWithReversal = CalculateCRCWithBitReversal(data);
Console.WriteLine($"CRC with bit reversal: 0x{crcWithReversal:X4}");
}
}
```
这段代码包含两个主要方法:
1. `CalculateCRC`: 实现标准的CRC-16计算。
2. `CalculateCRCWithBitReversal`: 实现输入和输出都反转的CRC-16计算。
`ReverseBits`方法是用来反转位的辅助函数。
在`Main`方法中,我们测试了这两计算方法。您可以根据需要修改输入数据。
阅读全文
相关推荐


















