Hash.String.cs 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using System;
  2. //-----------------------------------------------------------------------------
  3. // Hash
  4. // 重点计算字符串的 Hash
  5. // 算法及结果, 与 Hash.String.hpp 完全一致
  6. //-----------------------------------------------------------------------------
  7. internal static class StringHash32
  8. {
  9. private static readonly UInt32 _FNV_offset_basis_32 = 2166136261U;
  10. private static readonly UInt32 _FNV_prime_32 = 16777619U;
  11. internal static UInt32 From (string name)
  12. {
  13. var Hash = _FNV_offset_basis_32;
  14. foreach (var ch in name)
  15. {
  16. UInt32 w = ch;
  17. Hash ^= w;
  18. Hash *= _FNV_prime_32;
  19. }
  20. return Hash;
  21. }
  22. }
  23. internal static class StringHash64
  24. {
  25. private static readonly UInt64 _FNV_offset_basis_64 = 14695981039346656037UL; // 0xcbf29ce484222325
  26. private static readonly UInt64 _FNV_prime_64 = 1099511628211UL; // 0x00000100000001b3
  27. internal static UInt64 From (string name)
  28. {
  29. var Hash = _FNV_offset_basis_64;
  30. foreach (var ch in name)
  31. {
  32. UInt64 w = ch;
  33. Hash ^= w;
  34. Hash *= _FNV_prime_64;
  35. }
  36. return Hash;
  37. }
  38. }