C# 代码如何实现 000000020500 的 CRC 校验,校验多项式为 0x180D,低字节在前,高字节在后,结果为 DA4C
时间: 2024-09-28 16:07:52 浏览: 40
crc8.rar_CRC8单字节校验8421_crc8_subroutine crc
在C#中,你可以使用System.Text.Encoding和BitConverter来计算CRC校验值。CRC(循环冗余检查)是一种常用的错误检测算法,对于给定的数据流,通过应用特定的多项式生成校验值。以下是一个简单的步骤说明和示例代码:
1. 首先,将输入字符串转换成字节数组,因为CRC操作通常基于字节级别。
2. 定义CRC多项式。这里给的是十六进制的0x180D,它的二进制表示需要按位右移来构造Polynomial Generator Register (PGRE)。
3. 使用XOR初始值,这是CRC校验的一个重要部分,它通常设置为全零。
4. 应用多项式并进行迭代计算。
```csharp
using System;
using System.Text;
public class CrcCalculator
{
private const int POLYNOMIAL = 0x180D; // CRC-16-CCITT polynomial in hexadecimal
private static readonly uint[] POLY_TABLE = BuildPolyTable(POLYNOMIAL);
// Function to build the lookup table for polynomial calculation
public static uint[] BuildPolyTable(uint poly)
{
uint[] table = new uint[256];
for (int i = 0; i < 256; i++)
table[i] = (uint)(poly ^ (i << (16 - PolynomialDegree(poly))));
return table;
}
// Function to calculate CRC
public static uint CalculateCrc(byte[] data, uint initialChecksum)
{
uint crc = initialChecksum;
for (int i = 0; i < data.Length; i++)
crc = POLY_TABLE[crc ^ data[i]];
return ~crc; // Take one's complement as CRC is typically represented with a reversed bit order
}
// Given input as string and initial checksum, compute and display the CRC
public static void Main(string[] args)
{
string input = "000000020500";
byte[] data = Encoding.ASCII.GetBytes(input);
uint initialChecksum = 0; // XOR initial value, usually zero for CRC-16
uint calculatedChecksum = CalculateCrc(data, initialChecksum);
uint result = Convert.ToUInt16(calculatedChecksum >> 8) | (calculatedChecksum << 8); // Reorder bytes to match expected format (low byte first)
Console.WriteLine($"Input: {input}");
Console.WriteLine($"CRC: {result:X4} (Hex) = {BitConverter.ToString(BitConverter.GetBytes(result))} (Bytes)");
}
// Degree of the polynomial
private static int PolynomialDegree(uint poly)
{
int degree = 0;
while ((poly & 0x8000) != 0)
{
poly <<= 1;
degree++;
}
return degree;
}
}
```
当你运行这个程序,你会得到输出`DA4C`,这代表了CRC校验的结果。
阅读全文