我正试图在C#程序中实现crc计算。我得到了设备C程序的代码片段,但我无法将其实现到我的程序中。
这是我得到的代码:
uint16_t oblicz_crc(uint8_t* buffer, uint8_t length)
{
uint16_t crc = 0xffff;
uint8_t i, j;
for(i=0;i<length;i++)
{
crc ^= *(buffer+i);
for(j=0;j<8;j++)
{
3
if(crc & 0x0001)
{
crc >>= 1;
crc ^= 0xA001;
}
else
{
crc >>= 1;
}
}
}
return(crc);
}
我的程序中已经有一个代码。我假设一些二进制运算符、"if((crc&0x0001)==1)"片段或某些数据类型是错误的。你能帮我做这个吗?
public void Send_Frame(byte[] buffer)
{
byte[] checksum = Crc(buffer); //Array.Reverse(arg) ??
Array.Resize(ref buffer, buffer.Length + 2);
Array.Copy(checksum, 0, buffer, buffer.Length - 2, 2);
#if DEBUG
richTextBoxPreview.AppendText( BitConverter.ToString(buffer) + "n");
#endif
//Port.Write(buffer);
}
private byte[] Crc(byte[] buffer)
{
UInt16 crc = 0xFFFF;
int i, j;
for (i = 0; i < buffer.Length; i++)
{
crc ^= (ushort)(BitConverter.ToUInt16(buffer, 0) + (byte)i);
for (j = 0; j < 8; j++)
{
if ((crc & 0x0001) == 1)
{
crc >>= 1;
crc ^= 0xA001;
}
else
{
crc >>= 1;
}
}
}
return BitConverter.GetBytes(crc);
}
附言:这个问题是关于我的具体代码片段。当我得到答案时,最好删除它吗?还是我应该离开它?
问题出在这一行:
crc ^= (ushort)(BitConverter.ToUInt16(buffer, 0) + (byte)i);
在原始代码中:
crc ^= *(buffer+i);
原始代码将i添加到缓冲区指针,并取消对该位置的引用。如果您将代码更改为:
crc ^= (ushort)(buffer[i]);
那么你实际上也在做同样的手术。
这行得通吗?
public static ushort oblicz_crc(byte[] buffer, int length)
{
unchecked
{
ushort crc = 0xffff;
for (int i = 0; i < length; i++)
{
crc ^= buffer[i];
for (int j = 0; j < 8; j++)
{
if ((crc & 0x0001) != 0)
{
crc >>= 1;
crc ^= 0xA001;
}
else
{
crc >>= 1;
}
}
}
return (crc);
}
}