简体   繁体   English

如何在python中将字符串转换为唯一的十进制数字?

[英]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.

相关问题 如何将字符串转换为十进制数以在 Python 中进行算术运算? - How do I convert a string into a decimal number for arithmetic manipulation in Python? 如何在python中将unicode字符串转换为十进制数字? - How to convert unicode string to decimal number in python? 如何在 Python 中将小数转换为数字(带小数) - How to convert a Decimal to Number(with decimal numbers) in Python 如何将 sympy 十进制数转换为 Python 十进制数? - How to convert a sympy decimal number to a Python decimal? 如何将数字转换为与python中输入格式相同的字符串? - How do I convert a number to a string in the same format as the input in python? 如何在 Python 中将货币字符串转换为浮点数? - How do I convert a currency string to a floating point number in Python? 如何将十进制数转换为python中的字节列表 - How do you convert a decimal number into a list of bytes in python 如何在德语区域设置中将字符串转换为Python Decimal(使用逗号而不是点) - How do I convert a string to a Python Decimal in German locale (with comma instead of a point) 如何使用Python将LabVIEW十进制日期转换为字符串日期时间格式? - How do I convert a LabVIEW decimal date into a string datetime format using Python? 如何将浮点数转换为字符串,但转换为小数点后第六位-Python - How can I convert a float to a string, but to the sixth decimal - Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM