Last active
August 29, 2015 14:14
-
-
Save khellang/699b56cadb2f4d922461 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class Crc32 | |
{ | |
private const uint Seed = 0xFFFFFFFF; | |
private const uint Polynomial = 0xEDB88320; | |
private static readonly uint[] LookupTable; | |
static Crc32() | |
{ | |
LookupTable = CreateLookupTable(); | |
} | |
public static uint CalculateChecksum(string value) | |
{ | |
return CalculateChecksum(Encoding.UTF8.GetBytes(value)); | |
} | |
public static uint CalculateChecksum(byte[] buffer) | |
{ | |
return buffer.Aggregate(Seed, Lookup, value => value ^ Seed); | |
} | |
private static uint Lookup(uint value, byte b) | |
{ | |
return (value >> 8) ^ LookupTable[(value & 0xFF) ^ b]; | |
} | |
private static uint[] CreateLookupTable() | |
{ | |
var table = new uint[256]; | |
for (var i = 0; i < 256; i++) | |
{ | |
var entry = (uint) i; | |
for (var j = 0; j < 8; j++) | |
{ | |
entry = (entry & 1) == 1 ? (entry >> 1) ^ Polynomial : entry >> 1; | |
} | |
table[i] = entry; | |
} | |
return table; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment