Skip to content

Instantly share code, notes, and snippets.

@lmas
Created June 12, 2017 16:14
Show Gist options
  • Save lmas/664afa94f922c1e58d5c3d73aed98f3f to your computer and use it in GitHub Desktop.
Save lmas/664afa94f922c1e58d5c3d73aed98f3f to your computer and use it in GitHub Desktop.
djb2, a non-cryptographic hash function
package djb2
// For when you ever need to implement a dictionary hash function,
// that's good enough, simple and fast.
//
// WARNING:
// Not cryptographicly secure!
//
// Source: https://en.wikipedia.org/wiki/DJB2
//
// EXAMPLE
//
//func main() {
// fmt.Println(djb2("a"))
// fmt.Println(djb2("b"))
//}
func djb2(s string) int64 {
var hash int64 = 5381
for _, c := range s {
hash = ((hash << 5) + hash) + int64(c)
// the above line is an optimized version of the following line:
//hash = hash * 33 + int64(c)
// which is easier to read and understand...
}
return hash
}
@Gaurav-Singh-97
Copy link

Gaurav-Singh-97 commented Jul 5, 2019

Source: https://en.wikipedia.org/wiki/DJB2
Wikipedia does not have an article with this exact name.

@lmas
Copy link
Author

lmas commented Jul 11, 2019

Guess that page was removed since I wrote this utility, 2 years ago or something

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment