GeneralHashFunctions.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. # !/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. def rs_hash(key):
  4. a = 378551
  5. b = 63689
  6. hash_value = 0
  7. for i in range(len(key)):
  8. hash_value = hash_value * a + ord(key[i])
  9. a = a * b
  10. return hash_value
  11. def js_hash(key):
  12. hash_value = 1315423911
  13. for i in range(len(key)):
  14. hash_value ^= ((hash_value << 5) + ord(key[i]) + (hash_value >> 2))
  15. return hash_value
  16. def pjw_hash(key):
  17. bits_in_unsigned_int = 4 * 8
  18. three_quarters = (bits_in_unsigned_int * 3) / 4
  19. one_eighth = bits_in_unsigned_int / 8
  20. high_bits = 0xFFFFFFFF << int(bits_in_unsigned_int - one_eighth)
  21. hash_value = 0
  22. test = 0
  23. for i in range(len(key)):
  24. hash_value = (hash_value << int(one_eighth)) + ord(key[i])
  25. test = hash_value & high_bits
  26. if test != 0:
  27. hash_value = ((hash_value ^ (test >> int(three_quarters))) & (~high_bits))
  28. return hash_value & 0x7FFFFFFF
  29. def elf_hash(key):
  30. hash_value = 0
  31. for i in range(len(key)):
  32. hash_value = (hash_value << 4) + ord(key[i])
  33. x = hash_value & 0xF0000000
  34. if x != 0:
  35. hash_value ^= (x >> 24)
  36. hash_value &= ~x
  37. return hash_value
  38. def bkdr_hash(key):
  39. seed = 131 # 31 131 1313 13131 131313 etc..
  40. hash_value = 0
  41. for i in range(len(key)):
  42. hash_value = (hash_value * seed) + ord(key[i])
  43. return hash_value
  44. def sdbm_hash(key):
  45. hash_value = 0
  46. for i in range(len(key)):
  47. hash_value = ord(key[i]) + (hash_value << 6) + (hash_value << 16) - hash_value;
  48. return hash_value
  49. def djb_hash(key):
  50. hash_value = 5381
  51. for i in range(len(key)):
  52. hash_value = ((hash_value << 5) + hash_value) + ord(key[i])
  53. return hash_value
  54. def dek_hash(key):
  55. hash_value = len(key);
  56. for i in range(len(key)):
  57. hash_value = ((hash_value << 5) ^ (hash_value >> 27)) ^ ord(key[i])
  58. return hash_value
  59. def bp_hash(key):
  60. hash_value = 0
  61. for i in range(len(key)):
  62. hash_value = hash_value << 7 ^ ord(key[i])
  63. return hash_value
  64. def fnv_hash(key):
  65. fnv_prime = 0x811C9DC5
  66. hash_value = 0
  67. for i in range(len(key)):
  68. hash_value *= fnv_prime
  69. hash_value ^= ord(key[i])
  70. return hash_value
  71. def ap_hash(key):
  72. hash_value = 0xAAAAAAAA
  73. for i in range(len(key)):
  74. if (i & 1) == 0:
  75. hash_value ^= ((hash_value << 7) ^ ord(key[i]) * (hash_value >> 3))
  76. else:
  77. hash_value ^= (~((hash_value << 11) + ord(key[i]) ^ (hash_value >> 5)))
  78. return hash_value