我正在尝试计算串行通信的校验和。所以我做了一个字节数组的数据缓冲区。我不知道如何使用此字节的数据缓冲区数组来实现此功能。因为此函数的参数类型是字节指针。如何使用此功能?
byte[] arrayForChecksum // for databuffer
// calculating a checksum for C#
public unsafe static ushort CalcCRC(byte * pDataBuffer, uint usDataLen)
{
byte nTemp;
ushort wCRCWord = 0xFFFF;
while ((usDataLen--) != 0)
{
nTemp = (byte)(wCRCWord ^*pDataBuffer++);
wCRCWord >>= 8;
wCRCWord ^= TABLE_CRCVALUE[nTemp];
}
return wCRCWord;
}
// original code in C
unsigned short CalcCRC(unsigned char* pDataBuffer, unsigned long usDataLen)
{
unsigned char nTemp;
unsigned short wCRCWord = 0xFFFF;
while (usDataLen--)
{
nTemp = wCRCWord ^ *(pDataBuffer++);
wCRCWord >>= 8;
wCRCWord ^= TABLE_CRCVALUE[nTemp];
}
return wCRCWord;
}
您可以将校验和用于任何内容。例如,您可以将将从数据库中获取的文本转换为字节数组并计算校验和值。
public class Crc16
{
private const ushort polynomial = 0xA001;
private static readonly ushort[] refTable = new ushort[256];
public Crc16()
{
GenerateReferanceTable();
}
private void GenerateReferanceTable()
{
ushort value;
ushort temp;
for (ushort i = 0; i < refTable.Length; ++i)
{
value = 0;
temp = i;
for (byte j = 0; j < 8; ++j)
{
if (((value ^ temp) & 0x0001) != 0)
{
value = (ushort)((value >> 1) ^ polynomial);
}
else
{
value >>= 1;
}
temp >>= 1;
}
refTable[i] = value;
}
}
public ushort Calculate(byte[] bytes)
{
ushort crc = 0;
for (int i = 0; i < bytes.Length; ++i)
{
byte index = (byte)(crc ^ bytes[i]);
crc = (ushort)((crc >> 8) ^ refTable[index]);
}
return crc;
}
}
用法:
byte[] bytes = new byte[] { 0, 1, 2, 3, 204, 120 };
Crc16 crc16 = new Crc16();
ushort checksum = crc16.Calculate(bytes);
string data = "Calculate Checksum";
byte[] bytesFromString = Encoding.ASCII.GetBytes(someString);
ushort checksumForString = crc16.Calculate(bytesFromString);
您也可以签出我的项目。
https://github.com/hidayetcolkusu/ChecksumManager