CRC32.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. /// <summary>
  6. /// CRC32相关工具集
  7. /// </summary>
  8. public partial class Utils
  9. {
  10. /// <summary>
  11. /// key
  12. /// </summary>
  13. private static ulong[] Crc32Table;
  14. /// <summary>
  15. /// 获取指定字符串的CRC32值
  16. /// </summary>
  17. /// <param name="str">源串</param>
  18. /// <returns>经crc32换算后的数值</returns>
  19. public static ulong CRC32(string str)
  20. {
  21. GetCRC32Tale();
  22. byte[] buffer = System.Text.ASCIIEncoding.ASCII.GetBytes(str);
  23. ulong value = 0xffffffff;
  24. int len = buffer.Length;
  25. for (int i = 0; i < len; i++)
  26. {
  27. value = (value >> 8) ^ Crc32Table[(value & 0xFF) ^ buffer[i]];
  28. }
  29. return value ^ 0xffffffff;
  30. }
  31. /// <summary>
  32. /// 创建CRC32因子
  33. /// </summary>
  34. private static void GetCRC32Tale()
  35. {
  36. ulong Crc;
  37. Crc32Table = new ulong[256];
  38. int i, j;
  39. for (i = 0; i < 256; i++)
  40. {
  41. Crc = (ulong)i;
  42. for (j = 8; j > 0; j--)
  43. {
  44. if ((Crc & 1) == 1)
  45. {
  46. Crc = (Crc >> 1) ^ 0xEDB88320;
  47. }
  48. else
  49. {
  50. Crc >>= 1;
  51. }
  52. }
  53. Crc32Table[i] = Crc;
  54. }
  55. }
  56. }