c# - 将 CRC C 算法移植到 C#

标签 c# c crc

我在 C 中有这个函数,我需要将其移植到 C#。我已经做了一些尝试,但无法弄清楚我做错了什么。

多项式为 0x04C11DB7uL。

它不必包含 while 循环,我也尝试过使用 For 循环。

static uint32_t APPL_CalcCRC32(uint32_t u32Sum, uint8_t *pData, uint32_t count)
{

    uint8_t iCounter;
    uint32_t u32Word;
    uint64_t u64Sum;

    u64Sum = u32Sum;

    count = count / 4;  // number of bytes --> number of words

    // algorithm according to AN4187 (Figure 2)
    while (count--)
    {
        u32Word = *((uint32_t*)pData)++;

        u64Sum ^= u32Word;

        for (iCounter = 0; iCounter < (8 * 4); ++iCounter)
        {
            u64Sum <<= 1;

            if (u64Sum & 0x100000000)
            {
                u64Sum ^= 0x04C11DB7uL;
            }
        }
    }

    return (uint32_t)u64Sum;
}

这是我的尝试:

private uint CalculateBlockCheckSum( uint u32Sum, byte[] blockImage )
        {
            uint u32Word;
            ulong u64Sum = u32Sum;
            ulong comparisonValue = 0x100000000;
            int count = blockImage.Length / 4;
            int i = 0;
            while ( count-- >= 0 )
            {

                u32Word = blockImage[i++];
                u64Sum ^= u32Word;

                for ( byte iCounter = 0; iCounter < ( 8 * 4 ); ++iCounter )
                {
                    u64Sum <<= 1;

                    if ( ( u64Sum & comparisonValue ) != 0 )
                    {
                        u64Sum ^= 0x04C11DB7uL;
                    }
                }
            }
            return (uint)u64Sum;
        }

我的主要疑问是我的 C# 函数中的 u32Word 赋值和循环条件,对吗?

我的测试设置是 58 个数组( block ),每个 block 1024 字节。 但两个函数的输出并不相同。那么是我的功能错误还是其他原因?

最佳答案

您只需在移入数据 block 的下一个值时更改该行:

private uint CalculateBlockCheckSum(uint u32Sum, byte[] blockImage)
{
    uint u32Word;
    ulong u64Sum = u32Sum;
    ulong comparisonValue = 0x100000000;
    int count = blockImage.Length / sizeof(uint);
    int i = 0;
    while (count-- > 0)
    {
        u32Word = BitConverter.ToUInt32(blockImage,i*sizeof(uint));
        u64Sum ^= u32Word;

        for (byte iCounter = 0; iCounter < (8 * 4); ++iCounter)
        {
            u64Sum <<= 1;

            if ((u64Sum & comparisonValue) != 0)
            {
                u64Sum ^= 0x04C11DB7uL;
            }
        }
        i++;
    }
    return (uint)u64Sum;
}

关于c# - 将 CRC C 算法移植到 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58730848/

相关文章:

python - 如何在python中重建libmem_crc32_direct CRC函数?

c# - MVC3 范围属性 - 不允许值为零

c# - 如何在 C# 中正确处理密码

c# - 如何使用 lambda 表达式进行验证以验证某个小时是否为某个 "type"(必须为 hh :00 or hh:30)

c - 如何从main中的函数读取二维数组

c - _mm_crc32_u8 给出与引用代码不同的结果

c# - 等待在 C# 中创建文件

c - 如何在枚举对象中选择第 i 个元素

c - 在 C 中修复字母频率分析器

Perl 十六进制 CRC-16 位脚本