Hash function that prints an integer from 0 to 255?

I need a very simple hash function in Python that converts a string to an integer from 0 to 255.

For instance:

>>> hash_function("abc_123")
32
>>> hash_function("any-string-value")
99

It doesn't matter what an integer is, as long as I get the same integer every time the function is called.

I want to use an integer to generate a random subnet mask based on the network name.

+4
source share
1 answer

You can simply use the function module hash():

def onebyte_hash(s):
    return hash(s) % 256

This is what dictionaries and collections use (the hash module is the internal size of the table).

Demo:

>>> onebyte_hash('abc_123')
182
>>> onebyte_hash('any-string-value')
12

: Python 3.3 - , Python . , Python PYTHONHASHSEED ( 0 ), Python 2 3,2 3,2 - , .

hashlib.md5() ( ) :

import hashlib

try:
    # Python 2; Python 3 will throw an exception here as bytes are required
    hashlib.md5('')
    def onebyte_hash(s):
        return ord(hashlib.md5(s).digest()[0])
except TypeError:
    # Python 3; encode the string first, return first byte
    def onebyte_hash(s):
        return hashlib.md5(s.encode('utf8')).digest()[0]

MD5 - , Python -.

, ; Python , .

+13

Source: https://habr.com/ru/post/1655832/


All Articles