문제
.NET에서 문자열의 CRC32(순환 중복 체크섬)를 어떻게 계산합니까?
해결책
이 사람이 당신의 대답을 알고 있는 것 같습니다.
https://damieng.com/blog/2006/08/08/calculated_crc32_in_c_and_net
블로그가 사라지거나 URL이 손상된 경우에는 다음 Github 링크를 참조하세요.
블로그 게시물의 Crc32 클래스 사용법:
Crc32 crc32 = new Crc32();
String hash = String.Empty;
using (FileStream fs = File.Open("c:\\myfile.txt", FileMode.Open))
foreach (byte b in crc32.ComputeHash(fs)) hash += b.ToString("x2").ToLower();
Console.WriteLine("CRC-32 is {0}", hash);
다른 팁
파일이 아닌 문자열의 CRC32를 계산하려는 것 같으므로 여기에 좋은 예가 있습니다. https://rosettacode.org/wiki/CRC-32#C.23
코드가 사라질 경우:
/// <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
}
그리고 그것을 사용하려면 :
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/
제휴하지 않습니다 StackOverflow