Michael Sanders
2023-09-22 19:50:09 UTC
Greetings folks, just sharing the knowledge (& test posting using google groups).
Beware wordwrap...
function djb2(str, hash, i, char) {
# initialize hash to an arbitrary prime number
hash = 5381
n = length(str)
# iterate over characters and compute hash
for(i = 1; i <= n; i++) {
char = substr(str, i, 1)
# modulo simulates 32-bit unsigned integer
hash = (hash * 33 + ord(char)) % 2147483647
}
return hash
}
function ord(char) {
return (char ~ /[[:digit:]]/ ? int(char) : int(ord[char]))
}
BEGIN {
for(i=32;i<=126;i++) ord[sprintf("%c", i)] = i
print djb2("my key is...")
}
notes:
https://stackoverflow.com/questions/1579721/why-are-5381-and-33-so-important-in-the-djb2-algorithm
https://stackoverflow.com/questions/10696223/reason-for-the-number-5381-in-the-djb-hash-function
https://groups.google.com/g/comp.lang.c/c/lSKWXiuNOAk
https://en.wikipedia.org/wiki/Daniel_J._Bernstein
Beware wordwrap...
function djb2(str, hash, i, char) {
# initialize hash to an arbitrary prime number
hash = 5381
n = length(str)
# iterate over characters and compute hash
for(i = 1; i <= n; i++) {
char = substr(str, i, 1)
# modulo simulates 32-bit unsigned integer
hash = (hash * 33 + ord(char)) % 2147483647
}
return hash
}
function ord(char) {
return (char ~ /[[:digit:]]/ ? int(char) : int(ord[char]))
}
BEGIN {
for(i=32;i<=126;i++) ord[sprintf("%c", i)] = i
print djb2("my key is...")
}
notes:
https://stackoverflow.com/questions/1579721/why-are-5381-and-33-so-important-in-the-djb2-algorithm
https://stackoverflow.com/questions/10696223/reason-for-the-number-5381-in-the-djb-hash-function
https://groups.google.com/g/comp.lang.c/c/lSKWXiuNOAk
https://en.wikipedia.org/wiki/Daniel_J._Bernstein