【问题标题】:How could I use this function for calculating CHECKSUM我怎么能用这个函数来计算 CHECKSUM
【发布时间】:2020-05-14 05:50:36
【问题描述】:

我正在尝试计算串行通信的校验和。所以我为数据缓冲区制作了一个字节数组。 我不知道如何将这个数据缓冲区的字节数组用于这个功能。 因为这个函数的参数类型是字节指针。 如何使用这个功能?

byte[] arrayForChecksum // for databuffer

// calculating a checksum for C#
public unsafe static ushort CalcCRC(byte * pDataBuffer, uint usDataLen)
{
        byte nTemp;
        ushort wCRCWord = 0xFFFF;

        while ((usDataLen--) != 0)
        {
            nTemp = (byte)(wCRCWord ^*pDataBuffer++);
            wCRCWord >>= 8;
            wCRCWord ^= TABLE_CRCVALUE[nTemp];
        }

        return wCRCWord;
}


// original code in C
unsigned short CalcCRC(unsigned char* pDataBuffer, unsigned long usDataLen)
{       
    unsigned char nTemp;
    unsigned short wCRCWord = 0xFFFF;

    while (usDataLen--)
   {
        nTemp = wCRCWord ^ *(pDataBuffer++);
        wCRCWord >>= 8;
        wCRCWord ^= TABLE_CRCVALUE[nTemp];
    }

    return wCRCWord;
}

【问题讨论】:

    标签: c# checksum


    【解决方案1】:

    您可以对任何事情使用校验和。例如,您可以将从数据库中获取的文本转换为字节数组并计算校验和值。

    public class Crc16
    {
        private const ushort polynomial = 0xA001;
        private static readonly ushort[] refTable = new ushort[256];
    
        public Crc16()
        {
            GenerateReferenceTable();
        }
    
        private void GenerateReferenceTable()
        {
            ushort value;
            ushort temp;
    
            for (ushort i = 0; i < refTable.Length; ++i)
            {
                value = 0;
                temp = i;
    
                for (byte j = 0; j < 8; ++j)
                {
                    if (((value ^ temp) & 0x0001) != 0)
                    {
                        value = (ushort)((value >> 1) ^ polynomial);
                    }
                    else
                    {
                        value >>= 1;
                    }
    
                    temp >>= 1;
                }
    
                refTable[i] = value;
            }
        }
    
        public ushort Calculate(byte[] bytes)
        { 
            ushort crc = 0; 
    
            for (int i = 0; i < bytes.Length; ++i)
            {
                byte index = (byte)(crc ^ bytes[i]);
                crc = (ushort)((crc >> 8) ^ refTable[index]);
            } 
    
            return crc;
        }
    }
    

    用法:

    byte[] bytes = new byte[] { 0, 1, 2, 3, 204, 120 }; 
    Crc16 crc16 = new Crc16();
    ushort checksum = crc16.Calculate(bytes);
    
    
    string data = "Calculate Checksum";
    byte[] bytesFromString = Encoding.ASCII.GetBytes(data);
    ushort checksumForString = crc16.Calculate(bytesFromString); 
    

    你也可以看看我的项目。

    https://github.com/hidayetcolkusu/ChecksumManager

    【讨论】:

      猜你喜欢
      • 2017-04-11
      • 2018-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多