C# crc32校验
时间: 2023-09-20 11:05:22 浏览: 67
在C#中,你可以使用以下代码来计算CRC32校验值:
```csharp
using System;
using System.IO;
using System.Security.Cryptography;
public class CRC32
{
private static readonly uint[] crcTable;
static CRC32()
{
crcTable = new uint[256];
const uint poly = 0xEDB88320;
for (uint i = 0; i < 256; i++)
{
uint crc = i;
for (int j = 0; j < 8; j++)
{
if ((crc & 1) == 1)
{
crc = (crc >> 1) ^ poly;
}
else
{
crc >>= 1;
}
}
crcTable[i] = crc;
}
}
public static uint ComputeChecksum(byte[] bytes)
{
uint crc = 0xFFFFFFFF;
foreach (byte b in bytes)
{
byte index = (byte)((crc ^ b) & 0xFF);
crc = (crc >> 8) ^ crcTable[index];
}
return ~crc;
}
public static uint ComputeChecksum(string filePath)
{
using (FileStream fs = File.OpenRead(filePath))
{
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)
{
for (int i = 0; i < bytesRead; i++)
{
byte index = (byte)((crc ^ buffer[i]) & 0xFF);
crc = (crc >> 8) ^ crcTable[index];
}
}
}
return ~crc;
}
}
```
要计算给定字节数组的CRC32校验值,可以使用`ComputeChecksum`方法。例如:
```csharp
byte[] data = Encoding.UTF8.GetBytes("Hello, World!");
uint checksum = CRC32.ComputeChecksum(data);
Console.WriteLine(checksum.ToString("X8")); // 输出校验值的十六进制表示
```
要计算给定文件的CRC32校验值,可以使用`ComputeChecksum`方法,并传递文件路径作为参数。例如:
```csharp
string filePath = "path/to/file.txt";
uint checksum = CRC32.ComputeChecksum(filePath);
Console.WriteLine(checksum.ToString("X8")); // 输出校验值的十六进制表示
```
请注意,代码中的CRC32实现使用了预先计算的CRC表,这可以提高计算速度。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)