【问题标题】:CRC function. Converting C to C#CRC 函数。将 C 转换为 C#
【发布时间】:2010-11-15 03:35:34
【问题描述】:

我需要将这些 C 函数转换为 C#。只是想仔细检查我是否做得对。谢谢!

C 代码:

unsigned short Crc;

unsigned short update_crc(unsigned short crc, char c) {
    char i;

    crc ^= (unsigned short)c<<8;
    for (i=0; i<8; i++) {
        if (crc & 0x8000) crc = (crc<<1)^0x1021;
        else crc <<=1;
    }
    return crc;
}


void exampleCRC(void){

 #define INITIAL_CRC 0xffff

unsigned short Crc = INITIAL_CRC;
record_t record;

    for (byteCount=0; byteCount<sizeof(record_t); byteCount++) {
        Crc = update_crc(Crc, record[byteCount] );
    }
}

C# 代码:

ushort UpdateCrc(ref ushort crc, byte b)
{
    crc ^= (ushort)(b << 8);

    for (int i = 0; i < 8; i++)
    {
        if ((crc & 0x8000) > 0)
            crc = (ushort)((crc << 1) ^ 0x1021);
        else
            crc <<= 1;
    }

    return crc;
}

ushort CalcCrc(byte[] data)
{
    ushort crc = 0xFFFF;

    for (int i = 0; i < data.Length; i++)
        crc = UpdateCrc(ref crc, data[i]);

    return crc;
}

【问题讨论】:

    标签: c# c crc


    【解决方案1】:

    对我来说似乎很好,除了你真的不需要 ref 参数 UpdateCrc 因为无论如何你要返回修改后的值。

    【讨论】:

      【解决方案2】:

      您是否尝试过对各种不同的值进行测试?

      也可以让它们成为 static 函数(如果这不是你的计划的话),因为它们似乎不需要访问任何对象状态。

      【讨论】:

        猜你喜欢
        • 2017-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-24
        • 2018-10-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多