StringHashHelper.cs 925 B

12345678910111213141516171819202122232425262728293031323334
  1. using System;
  2. using System.Text;
  3. namespace ET
  4. {
  5. public static class StringHashHelper
  6. {
  7. // bkdr hash
  8. public static long GetLongHashCode(this string str)
  9. {
  10. const uint seed = 1313; // 31 131 1313 13131 131313 etc..
  11. ulong hash = 0;
  12. for (int i = 0; i < str.Length; ++i)
  13. {
  14. char c = str[i];
  15. byte high = (byte)(c >> 8);
  16. byte low = (byte)(c & byte.MaxValue);
  17. hash = hash * seed + high;
  18. hash = hash * seed + low;
  19. }
  20. return (long)hash;
  21. }
  22. public static int Mode(this string strText, int mode)
  23. {
  24. if (mode <= 0)
  25. {
  26. throw new Exception($"string mode < 0: {strText} {mode}");
  27. }
  28. return (int)((ulong)strText.GetLongHashCode() % (uint)mode);
  29. }
  30. }
  31. }