[英]How do I convert a string into a unique decimal number in python?
I need to convert a string, say for instance "Hello world" into a unique decimal number. 我需要将一个字符串(例如“ Hello world”)转换为唯一的十进制数字。 By unique I mean that the number should be different even if a tiny bit of the string is changed.
唯一的意思是即使字符串的一小部分更改,数字也应该不同。 Furthermore, this process must be reversible.
此外,该过程必须是可逆的。 This is the process I need:
这是我需要的过程:
a = "Hello world"
b = someFunction(a)
print(b) --> 4324234
c = inverseOfSomeFunction(b)
print(c) --> "Hello world"
I looked through python documentation however I did not find an answer.. 我查看了python文档,但没有找到答案。
a="Hello WORLD"
def toBigInt(s):
ret=0
for i,j in enumerate(s):
ret+= ord(j)<<(i*8)
return ret
def fromBigInt(i):
s=""
while i>0:
s+=chr(i&0xff)
i=i>>8
return s
i = toBigInt(a)
print i
print fromBigInt(i)
This works the following: ord()
takes the integer representation for one character. 这样做的工作如下:
ord()
采用一个字符的整数表示。 Thats between 0 and 255. 多数民众赞成在0到255之间。
The <<(i*8)
shifts the next letter by 8 bits. <<(i*8)
将下一个字母移位8位。 Its the same as *i*265
just more to the point. 它与
*i*265
仅在于一点。
The decoding Function always takes the lowest 8 bits (i%0xff) and decodes them. 解码功能始终采用最低的8位(i%0xff)进行解码。 Then it shifts the remaining number 8 bits down.
然后将剩余数字向下移动8位。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.