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;
}