C# CRC-16-CCITT 0x8408 Polynomial. Help needed

笑着哭i 提交于 2019-12-25 18:25:43

问题


I am new in communications programming. Basically, I need to get the hex equivalent of the CRC output. I have a hex string which is the parameter -

EE0000000015202020202020202020202020323134373030353935

This is concatenation of two strings. The output I need is E6EB in hex or 59115 in ushort. I tried different approaches based on what I found in the web but to no avail. The polynomial that I should be using is 0x8408, which is [CRC-16-CCITT][1], http://en.wikipedia.org/wiki/Polynomial_representations_of_cyclic_redundancy_checks.

I tried this approach, CRC_CCITT Kermit 16 in C#, but the output is incorrect. I also tried the bitwise ~ operator as some suggested for reverse computation, but still failed.

Any help is very much appreciated.


回答1:


I found a solution and I'll post them in case someone will encounter the same.

private ushort CCITT_CRC16(string strInput)
{
        ushort data;
        ushort crc = 0xFFFF;
        byte[] bytes = GetBytesFromHexString(strInput);
        for (int j = 0; j < bytes.Length; j++)
        {
            crc = (ushort)(crc ^ bytes[j]);
            for (int i = 0; i < 8; i++)
            {
                if ((crc & 0x0001) == 1)
                    crc = (ushort)((crc >> 1) ^ 0x8408);
                else
                    crc >>= 1;
            }
        }
        crc = (ushort)~crc;
        data = crc;
        crc = (ushort)((crc << 8) ^ (data >> 8 & 0xFF));
        return crc;
}

private 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)
            {
                throw ex;
            }
        }
        return bytArOutput;
}

import System.Runtime.Remoting.Metadata.W3cXsd2001 for SoapHexBinary.




回答2:


RevEng reports:

% ./reveng -s -w 16 EE0000000015202020202020202020202020323134373030353935e6eb
width=16  poly=0x1021  init=0xffff  refin=true  refout=true  xorout=0xffff  check=0x906e  name="X-25"

So there's your CRC. Note that the CRC is reflected, where 0x8408 is 0x1021 reflected.



来源:https://stackoverflow.com/questions/30496223/c-sharp-crc-16-ccitt-0x8408-polynomial-help-needed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!