【发布时间】:2014-05-16 14:57:03
【问题描述】:
我正在尝试使用 C# 生成 CRC-16。我用于 RS232 的硬件要求输入字符串为 HEX。下面的截图显示了正确的转换,为了测试,我需要 8000 为 0xC061,但是生成 CRC-16 的 C# 方法必须能够转换任何给定的 HEX 字符串。
我尝试过使用 Nito.KitchenSink.CRC
我也试过下面的,当输入 8000 时会生成 8009 -
public string CalcCRC16(string strInput)
{
ushort crc = 0x0000;
byte[] data = GetBytesFromHexString(strInput);
for (int i = 0; i < data.Length; i++)
{
crc ^= (ushort)(data[i] << 8);
for (int j = 0; j < 8; j++)
{
if ((crc & 0x8000) > 0)
crc = (ushort)((crc << 1) ^ 0x8005);
else
crc <<= 1;
}
}
return crc.ToString("X4");
}
public Byte[] GetBytesFromHexString(string strInput)
{
Byte[] bytArOutput = new Byte[] { };
if (!string.IsNullOrEmpty(strInput) && strInput.Length % 2 == 0)
{
SoapHexBinary hexBinary = null;
try
{
hexBinary = SoapHexBinary.Parse(strInput);
if (hexBinary != null)
{
bytArOutput = hexBinary.Value;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
return bytArOutput;
}
【问题讨论】:
-
好的,所以有一些代码可以生成 CRC(我假设)。具体的问题/疑问是什么?
-
问题是生成的CRC不正确使用上面的代码。我将使用其当前输出更新问题。
-
输入“8000” - 是十进制 8000、十六进制 8000 还是字符串“8000”?
-
设备要求为HEX
-
@MattBaughan 不,这不是问题;计算机实际上不会以十六进制或十进制或其他任何方式说话。他们只有数字。我需要知道的是:you(不是机器)所说的 8000 是什么意思? CRC 在字节上运行。我需要知道我们正在散列的字节序列。我什至无需尝试就可以将 8000 解释为大约 15 个字节的序列。我需要知道哪个。