首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何计算字符串的CRC32

如何计算字符串的CRC32
EN

Stack Overflow用户
提问于 2008-08-11 19:41:20
回答 2查看 97.3K关注 0票数 47

如何在.NET中计算字符串的循环冗余校验和( CRC32 )?

EN

回答 2

Stack Overflow用户

发布于 2018-08-20 06:01:11

由于您似乎希望计算字符串(而不是文件)的CRC32,因此这里有一个很好的示例:https://rosettacode.org/wiki/CRC-32#C.23

如果代码消失了:

代码语言:javascript
复制
/// <summary>
/// Performs 32-bit reversed cyclic redundancy checks.
/// </summary>
public class Crc32
{
    #region Constants
    /// <summary>
    /// Generator polynomial (modulo 2) for the reversed CRC32 algorithm. 
    /// </summary>
    private const UInt32 s_generator = 0xEDB88320;
    #endregion

    #region Constructors
    /// <summary>
    /// Creates a new instance of the Crc32 class.
    /// </summary>
    public Crc32()
    {
        // Constructs the checksum lookup table. Used to optimize the checksum.
        m_checksumTable = Enumerable.Range(0, 256).Select(i =>
        {
            var tableEntry = (uint)i;
            for (var j = 0; j < 8; ++j)
            {
                tableEntry = ((tableEntry & 1) != 0)
                    ? (s_generator ^ (tableEntry >> 1)) 
                    : (tableEntry >> 1);
            }
            return tableEntry;
        }).ToArray();
    }
    #endregion

    #region Methods
    /// <summary>
    /// Calculates the checksum of the byte stream.
    /// </summary>
    /// <param name="byteStream">The byte stream to calculate the checksum for.</param>
    /// <returns>A 32-bit reversed checksum.</returns>
    public UInt32 Get<T>(IEnumerable<T> byteStream)
    {
        try
        {
            // Initialize checksumRegister to 0xFFFFFFFF and calculate the checksum.
            return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => 
                      (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8)));
        }
        catch (FormatException e)
        {
            throw new CrcException("Could not read the stream out as bytes.", e);
        }
        catch (InvalidCastException e)
        {
            throw new CrcException("Could not read the stream out as bytes.", e);
        }
        catch (OverflowException e)
        {
            throw new CrcException("Could not read the stream out as bytes.", e);
        }
    }
    #endregion

    #region Fields
    /// <summary>
    /// Contains a cache of calculated checksum chunks.
    /// </summary>
    private readonly UInt32[] m_checksumTable;

    #endregion
}

并使用它:

代码语言:javascript
复制
var arrayOfBytes = Encoding.ASCII.GetBytes("The quick brown fox jumps over the lazy dog");

var crc32 = new Crc32();
Console.WriteLine(crc32.Get(arrayOfBytes).ToString("X"));

您可以在此处测试输入/输出值:https://crccalc.com/

票数 12
EN

Stack Overflow用户

发布于 2020-04-29 14:46:09

使用上一个答案中的逻辑,这是我的观点:

代码语言:javascript
复制
public class CRC32
{
    private readonly uint[] ChecksumTable;
    private readonly uint Polynomial = 0xEDB88320;

    public CRC32()
    {
        ChecksumTable = new uint[0x100];

        for (uint index = 0; index < 0x100; ++index)
        {
            uint item = index;
            for (int bit = 0; bit < 8; ++bit)
                item = ((item & 1) != 0) ? (Polynomial ^ (item >> 1)) : (item >> 1);
            ChecksumTable[index] = item;
        }
    }

    public byte[] ComputeHash(Stream stream)
    {
        uint result = 0xFFFFFFFF;

        int current;
        while ((current = stream.ReadByte()) != -1)
            result = ChecksumTable[(result & 0xFF) ^ (byte)current] ^ (result >> 8);

        byte[] hash = BitConverter.GetBytes(~result);
        Array.Reverse(hash);
        return hash;
    }

    public byte[] ComputeHash(byte[] data)
    {
        using (MemoryStream stream = new MemoryStream(data))
            return ComputeHash(stream);
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8128

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档