Created
July 23, 2020 00:17
-
-
Save scheler/26a942d34fb5576a68c111b05ac3fabe to your computer and use it in GitHub Desktop.
String hash function in Lua
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function hash(str) | |
h = 5381; | |
for c in str:gmatch"." do | |
h = ((h << 5) + h) + string.byte(c) | |
end | |
return h | |
end |
You'll want to mod by 2^31 to keep it within 32 bits or you'll get a double floating point number eventually.
function hash(str)
h = 5381;
for c in str:gmatch"." do
h = math.fmod(((h << 5) + h) + string.byte(c), 2147483648)
end
return h
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
(I am not sure if the
h*32 + h
orh<<5 + h
is really faster than justh*33
)