【问题标题】:Incorrect CRC8 checksum computationCRC8 校验和计算不正确
【发布时间】:2017-06-26 19:49:34
【问题描述】:

我得到了这个类来计算一个字节[]的 CRC8 校验和:

public static class Crc8
    {
        static byte[] table = new byte[256];
        // x8 + x7 + x6 + x4 + x2 + 1
        const byte poly = 0xd5;

        public static byte ComputeChecksum(params byte[] bytes)
        {
            byte crc = 0;
            if (bytes != null && bytes.Length > 0)
            {
                foreach (byte b in bytes)
                {
                    crc = table[crc ^ b];
                }
            }
            return crc;
        }

        static Crc8()
        {
            for (int i = 0; i < 256; ++i)
            {
                int temp = i;
                for (int j = 0; j < 8; ++j)
                {
                    if ((temp & 0x80) != 0)
                    {
                        temp = (temp << 1) ^ poly;
                    }
                    else
                    {
                        temp <<= 1;
                    }
                }
                table[i] = (byte)temp;
            }
        }
    }

我得到了主要的:

static void Main(string[] args)
{

    string number = "123456789";



    Console.WriteLine(Convert.ToByte(Crc8.ComputeChecksum(StringToByteArray(number))).ToString("x2"));

    Console.ReadLine();

}

private static byte[] StringToByteArray(string str)
{
    ASCIIEncoding enc = new ASCIIEncoding();
    return enc.GetBytes(str);
}

这导致 0xBC

但是,根据:http://www.scadacore.com/field-tools/programming-calculators/online-checksum-calculator/ 这是不正确的,因为 CheckSum8 Xor 的校验和是 0x31。

我哪里做错了?

【问题讨论】:

    标签: c# checksum crc


    【解决方案1】:

    在链接的站点上仅列出了一些 16 位和 32 位 CRC, CheckSum8Xor 不是 CRC。 0xBC 来自 8 位 CRC 称为“CRC-8/DVB-S2”,见http://reveng.sourceforge.net/crc-catalogue/1-15.htm

    【讨论】:

    • 谢谢,如果有人对此感兴趣,我已经发布了自己的答案。
    【解决方案2】:

    啊,好的,所以我过度解释了这个校验和计算。

    好吧,在这种情况下,这很容易:

    public static byte Checksum8XOR(byte[] data)
            {
                byte checksum = 0x00;
    
                for (int i = 0; i < data.Length; i++)
                {
    
                    checksum ^= data[i];
    
                }
    
    
                return checksum;
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-03
      • 2015-06-16
      • 1970-01-01
      • 1970-01-01
      • 2015-04-14
      • 2016-05-31
      • 2020-10-01
      • 1970-01-01
      相关资源
      最近更新 更多