hash function that outputs integer from 0 to 255?
<p>I need a very simple hash function in Python that will convert a string to an integer from 0 to 255.</p>

<p>For example:</p>

<pre><code>&gt;&gt;&gt; hash_function("abc_123")
32
&gt;&gt;&gt; hash_function("any-string-value")
99
</code></pre>

<p>It does not matter what the integer is as long as I get the same integer every time I call the function.</p>

<p>I want to use the integer to generate a random subnet mask based on the name of the network.</p>

<p>You could just use the modulus of the <a href="https://docs.python.org/3/library/functions.html#hash" rel="nofollow"><code>hash()</code> function</a> output:</p>

<pre><code>def onebyte_hash(s):
    return hash(s) % 256
</code></pre>

<p>This is what dictionaries and sets use (hash modulus the internal table size).</p>

<p>Demo:</p>

<pre><code>&gt;&gt;&gt; onebyte_hash('abc_123')
182
&gt;&gt;&gt; onebyte_hash('any-string-value')
12
</code></pre>

<p>Caveat: On Python 3.3 and up, <em>hash randomisation</em> is enabled by default, and <em>between restarts of Python</em> you'll get different values. The hash, then, is only stable if you don't restart the Python process or set <a href="https://docs.python.org/3/using/cmdline.html#envvar-PYTHONHASHSEED" rel="nofollow"><code>PYTHONHASHSEED</code></a> to a fixed decimal number (with <code>0</code> disabling it altogether). On Python 2 and 3.0 through to 3.2 hash randomisation is either not available or only enabled if you set a seed explicitly.</p>

<p>Another alternative is to just <a href="https://docs.python.org/3/library/functions.html#hash" rel="nofollow"><code>hashlib.md5()</code></a> and just take (integer value of) the first byte:</p>

<pre><code>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]
</code></pre>

<p>MD5 is a well-establish cryptographic hash, the output is stable across Python versions and independent of hash randomisation.</p>

<p>The disadvantage of the latter would be that it'd be marginally slower; Python caches string hashes on the string object, so retrieving the hash later on is fast and cheap most of the time.</p>

python hash integer