# 如何在[0：1]中将字符串哈希到浮点数？

```>>> myfunction(string_1)
0.26756754
>>> myfunction(string_2)
0.86764534```

random不符合我的需要,因为它不接受任何字符串作为输入/确定性参数.我正在寻找更像哈希函数的东西.

```from zlib import crc32

def bytes_to_float(b):
return float(crc32(b) & 0xffffffff) / 2**32```

```def str_to_float(s, encoding="utf-8"):
return bytes_to_float(s.encode(encoding))```

```>>> str_to_float(u"café")
0.5963937465567142```

```from struct import unpack
from hashlib import sha256

def bytes_to_float(b):
return float(unpack('L', sha256(b).digest()[:8])[0]) / 2**64```

```String length
Function    7       70      700     7000
b2f_crc32   0.34    0.38    0.87    5.59
b2f_md5     0.96    1.08    2.11    11.13
b2f_sha1    0.99    1.07    1.76    8.37
b2f_sha256  1.11    1.20    2.60    16.44
b2f_rnd     6.59    6.55    6.59    6.60```

```from __future__ import print_function
[...] # define b2f_crc32, b2f_md5 and so on.
for func in ("b2f_crc32", "b2f_md5", "b2f_sha1", "b2f_sha256", "b2f_rnd"):
for length in (7, 70, 700, 7000):
t = timeit('b2f(b"%s")'%(b"x"*length),
'from __main__ import %s as b2f' % func)
print("%.2f"%t, end="\t")
print()```