Reputation: 1192
I need to convert a string, say for instance "Hello world" into a unique decimal number. 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..
Upvotes: 0
Views: 288
Reputation: 1500
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. Thats between 0 and 255.
The <<(i*8)
shifts the next letter by 8 bits. Its the same as *i*265
just more to the point.
The decoding Function always takes the lowest 8 bits (i%0xff) and decodes them. Then it shifts the remaining number 8 bits down.
Upvotes: 1