Jump to content
Toggle menu
  • 17.3K articles
  • 8.2K files
  • 5 users
  • 280.7K edits
WoW Classic Wiki
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

Template:Breadcrumb2

  • This is a user-defined function that you can copy and paste into your addon. Replace <PREFIX> with your addon's prefix to avoid conflicts between different versions of these functions.
StringHash - by Mikk (talk · contr) -


Return a fair-quality 32-bit hash of a string

hashVal = <PREFIX>_StringHash("string")


Example

> print(PREFIX_StringHash(""))
1 
> print(<PREFIX>_StringHash("ab"))
3458343178
> print(<PREFIX>_StringHash("ba"))
3466747145
> print(<PREFIX>_StringHash("AB"))
2653593770
> print(<PREFIX>_StringHash("BA"))
2661997737
> print(<PREFIX>_StringHash("The quick brown fox jumps over the lazy dog"))
3402772626

Details

  • This algorithm is ~30% faster than a Lua implementation of the Java String.hashCode library call
  • The bit transmutation patterns and resulting collision rates are MUCH better than the results from the Java hash

Code

function <PREFIX>_StringHash(text)
  local counter = 1;
  local len = string.len(text); 
  for i = 1, len, 3 do 
    counter = math.mod(counter*8161, 4294967279) +  -- 2^32 - 17: Prime!
  	  (string.byte(text,i)*16776193) +
  	  ((string.byte(text,i+1) or (len-i+256))*8372226) +
  	  ((string.byte(text,i+2) or (len-i+256))*3932164);
  end; 
  return math.mod(counter, 4294967291); -- 2^32 - 5: Prime (and different from the prime in the loop)
end