Crc64.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using System.Collections.Generic;
  3. namespace SharpCompress.Compressors.Xz
  4. {
  5. internal static class Crc64
  6. {
  7. public const UInt64 DefaultSeed = 0x0;
  8. internal static UInt64[] Table;
  9. public const UInt64 Iso3309Polynomial = 0xD800000000000000;
  10. public static UInt64 Compute(byte[] buffer)
  11. {
  12. return Compute(DefaultSeed, buffer);
  13. }
  14. public static UInt64 Compute(UInt64 seed, byte[] buffer)
  15. {
  16. if (Table == null)
  17. Table = CreateTable(Iso3309Polynomial);
  18. return CalculateHash(seed, Table, buffer, 0, buffer.Length);
  19. }
  20. public static UInt64 CalculateHash(UInt64 seed, UInt64[] table, IList<byte> buffer, int start, int size)
  21. {
  22. var crc = seed;
  23. for (var i = start; i < size; i++)
  24. unchecked
  25. {
  26. crc = (crc >> 8) ^ table[(buffer[i] ^ crc) & 0xff];
  27. }
  28. return crc;
  29. }
  30. public static ulong[] CreateTable(ulong polynomial)
  31. {
  32. var createTable = new UInt64[256];
  33. for (var i = 0; i < 256; ++i)
  34. {
  35. var entry = (UInt64)i;
  36. for (var j = 0; j < 8; ++j)
  37. if ((entry & 1) == 1)
  38. entry = (entry >> 1) ^ polynomial;
  39. else
  40. entry = entry >> 1;
  41. createTable[i] = entry;
  42. }
  43. return createTable;
  44. }
  45. }
  46. }