Created
September 30, 2023 20:36
-
-
Save drewja/9a1ef71a0644924c8de87e70941a59c7 to your computer and use it in GitHub Desktop.
DJB hash function in python and some variants
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
"""DJB hash function in python and some variants""" | |
MAGIC_NUMBER = 0x1505 # 5381 | |
MASK_24 = (1 << 24) - 1 # 0xFFFFFF | |
MASK_32 = (1 << 32) - 1 # 0xFFFFFFFF | |
MASK_64 = (1 << 64) - 1 # 0xFFFFFFFFFFFFFFFF | |
def djb(string): | |
"""impl""" | |
_hash = MAGIC_NUMBER | |
while string: | |
_hash = (_hash << 5) + _hash + ord(string[0]) | |
string = string[1:] | |
return _hash | |
def djb_reversed(string): | |
"""DJB Hash on reversed string""" | |
return djb(string[::-1]) | |
def djb_24(string): | |
""" clamp djb hash to 24 bits via Xor folding""" | |
_hash = djb(string) | |
return ((_hash >> 24) ^ _hash) & MASK_24 | |
def djb_32(string): | |
""" clamp djb hash to 32 bits via Xor folding""" | |
_hash = djb(string) | |
return ((_hash >> 32) ^ _hash) & MASK_32 | |
def djb_64(string): | |
""" clamp djb hash to 64 bits via Xor folding""" | |
_hash = djb(string) | |
return ((_hash >> 64) ^ _hash) & MASK_64 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment