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 |
@karelbilek thanks
Also, this will work with older lua versions without <<
and will not use gmatch
function hash(str)
local h = 5381
for i = 1, #str do
h = h*32 + h + str:byte(i)
end
return h
end
(I am not sure if the h*32 + h
or h<<5 + h
is really faster than just h*33
)
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
Note that this is djb2 hash function (DJB is Daniel J. Bernstein)
http://www.cse.yorku.ca/~oz/hash.html
https://stackoverflow.com/questions/10696223/reason-for-the-number-5381-in-the-djb-hash-function
https://theartincode.stanis.me/008-djb2/