CRC.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. //
  2. // Copyright 2020 Electronic Arts Inc.
  3. //
  4. // The Command & Conquer Map Editor and corresponding source code is free
  5. // software: you can redistribute it and/or modify it under the terms of
  6. // the GNU General Public License as published by the Free Software Foundation,
  7. // either version 3 of the License, or (at your option) any later version.
  8. // The Command & Conquer Map Editor and corresponding source code is distributed
  9. // in the hope that it will be useful, but with permitted additional restrictions
  10. // under Section 7 of the GPL. See the GNU General Public License in LICENSE.TXT
  11. // distributed with this program. You should have received a copy of the
  12. // GNU General Public License along with permitted additional restrictions
  13. // with this program. If not, see https://github.com/electronicarts/CnC_Remastered_Collection
  14. using System;
  15. namespace MobiusEditor.Utility
  16. {
  17. public class CRC
  18. {
  19. static CRC()
  20. {
  21. for (var i = 0U; i < 256U; ++i)
  22. {
  23. uint crc = i;
  24. for (var j = 0U; j < 8U; ++j)
  25. {
  26. if ((crc & 1U) != 0U)
  27. {
  28. crc = (crc >> 1) ^ polynomial;
  29. }
  30. else
  31. {
  32. crc >>= 1;
  33. }
  34. }
  35. crcTable[i] = crc;
  36. }
  37. }
  38. public static uint Calculate(byte[] bytes)
  39. {
  40. if (bytes == null)
  41. {
  42. throw new ArgumentNullException("bytes");
  43. }
  44. uint remainder = 0xFFFFFFFFU;
  45. for (var i = 0; i < bytes.Length; ++i)
  46. {
  47. uint index = (remainder & 0xFF) ^ bytes[i];
  48. remainder = (remainder >> 8) ^ crcTable[index];
  49. }
  50. return ~remainder;
  51. }
  52. private static readonly uint[] crcTable = new uint[256];
  53. private const uint polynomial = 0xEDB88320;
  54. }
  55. }