8位模256和CRC

时间:2017-03-08 01:30:30

标签: c# crc

我在C#

中有一个用于协议标题的类
public class Header
{
    public UInt16 m_syncBytes;
    public UInt16 m_DestAddress;
    public UInt16 m_SourceAddress;

    public byte m_Protocol;
    public byte m_SequnceNumber;

    public byte m_Length;
    public byte m_HdrCrc;
}

我想计算从m_DestAddressm_Length

的8位模256个标题块字符总和

我在网上看到了很多16位CRC的例子。但是找不到8位Modulo 256和CRC。如果有人可以解释如何计算它,那就太好了。

1 个答案:

答案 0 :(得分:2)

这就是我的方式:

public byte GetCRC()
{
    int crc;  // 32-bits is more than enough to hold the sum and int will make it easier to math
    crc = (m_DestAddress & 0xFF) + (m_DestAddress >> 8);
    crc += (m_SourceAddress & 0xFF) + (m_SourceAddress >> 8);
    crc += m_Protocol;
    crc += m_SequenceNumber;
    crc += m_Length;

    return (byte)(crc % 256);  // Could also just do return (byte)(crc & 0xFF);
}