19

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

2 に答える 2

10

また、CRC16-CCITTをご希望の場合。

private ushort Crc16Ccitt(byte[] bytes)
{
    const ushort poly = 4129;
    ushort[] table = new ushort[256];
    ushort initialValue = 0xffff;
    ushort temp, a;
    ushort crc = initialValue;
    for (int i = 0; i < table.Length; ++i)
    {
        temp = 0;
        a = (ushort)(i << 8);
        for (int j = 0; j < 8; ++j)
        {
            if (((temp ^ a) & 0x8000) != 0)
                temp = (ushort)((temp << 1) ^ poly);
            else
                temp <<= 1;
            a <<= 1;
        }
        table[i] = temp;
    }
    for (int i = 0; i < bytes.Length; ++i)
    {
        crc = (ushort)((crc << 8) ^ table[((crc >> 8) ^ (0xff & bytes[i]))]);
    }
    return crc;
}
于 2016-01-22T09:29:50.070 に答える