【发布时间】:2016-09-06 22:26:22
【问题描述】:
我正在尝试在我的 C# 程序中实现 crc 计算。我有来自设备 C 程序的代码 sn-p,但我无法在我的程序中实现它。
这是我得到的代码:
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);
}
PS:这个问题是关于我的具体代码sn-p。当我得到答案时,最好将其删除吗?还是我应该离开它?
【问题讨论】:
-
放手让别人也能受益
标签: c# c bitwise-operators crc code-translation