Python: pearson_hashing.py

$ cat pearson_hashing.py
from random import shuffle

example_table = list(range(0, 256))
shuffle(example_table)

def hash8(message, table):
    hash = len(message) % 256
    for c in message:
        #hash = table[(hash+ord(c)) % 256]
        print(f'for c=\'{c}\', ord(c)={ord(c)}: {hash} ^ {ord(c)} => {hash ^ ord(c)} and table[hash ^ ord(c)] = {table[hash ^ ord(c)]}')
        hash = table[hash ^ ord(c)]
    return hash

if __name__ == '__main__':
    h = hash8('abc', example_table)
    print(f'hash8(\'abc\') => {h}')
$ python3 pearson_hashing.py
for c='a', ord(c)=97: 3 ^ 97 => 98 and table[hash ^ ord(c)] = 158
for c='b', ord(c)=98: 158 ^ 98 => 252 and table[hash ^ ord(c)] = 0
for c='c', ord(c)=99: 0 ^ 99 => 99 and table[hash ^ ord(c)] = 135
hash8('abc') => 135

Leave a Comment

Your email address will not be published.

12 − 12 =