Skip to content

Instantly share code, notes, and snippets.

@drewja
Created September 30, 2023 20:36
Show Gist options
  • Save drewja/9a1ef71a0644924c8de87e70941a59c7 to your computer and use it in GitHub Desktop.
Save drewja/9a1ef71a0644924c8de87e70941a59c7 to your computer and use it in GitHub Desktop.
DJB hash function in python and some variants
"""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