Python:将字母数字字符串可逆编码为整数 [英] Python: Reversibly encode alphanumeric string to integer
问题描述
我想将字符串(由字母数字字符组成)转换为整数,然后将该整数转换回字符串:
I want to convert a string (composed of alphanumeric characters) into an integer and then convert this integer back into a string:
string -> int->字符串
换句话说,我想用一个整数表示字母数字字符串。
In other words, I want to represent an alphanumeric string by an integer.
我找到了一个可行的解决方案,已将其包含在答案中,但我认为这不是最佳解决方案,并且我对其他想法/方法也很感兴趣。
I found a working solution, which I included in the answer, but I do not think it is the best solution, and I am interested in other ideas/methods.
请不要仅因为已经存在许多类似的问题就将其标记为重复项,所以我特别想要一种简单的方法来将字符串转换为整数,反之亦然。
Please don't tag this as duplicate just because a lot of similar questions already exist, I specifically want an easy way of transforming a string into an integer and vice versa.
这应该适用于包含字母数字字符的字符串,即包含数字和字母的字符串。
This should work for strings that contain alphanumeric characters, i.e. strings containing numbers and letters.
推荐答案
这是我到目前为止的内容:
Here's what I have so far:
字符串->字节
mBytes = m.encode("utf-8")
bytes-> int
bytes --> int
mInt = int.from_bytes(mBytes, byteorder="big")
int->字节
mBytes = mInt.to_bytes(((mInt.bit_length() + 7) // 8), byteorder="big")
bytes- ->字符串
bytes --> string
m = mBytes.decode("utf-8")
尝试一下:
m = "test123"
mBytes = m.encode("utf-8")
mInt = int.from_bytes(mBytes, byteorder="big")
mBytes2 = mInt.to_bytes(((mInt.bit_length() + 7) // 8), byteorder="big")
m2 = mBytes2.decode("utf-8")
print(m == m2)
以下是与上述相同的可重用版本:
Here is an identical reusable version of the above:
class BytesIntEncoder:
@staticmethod
def encode(b: bytes) -> int:
return int.from_bytes(b, byteorder='big')
@staticmethod
def decode(i: int) -> bytes:
return i.to_bytes(((i.bit_length() + 7) // 8), byteorder='big')
如果您使用的是Python< 3.6,请删除可选的类型注释。
If you're using Python <3.6, remove the optional type annotations.
测试:
>>> s = 'Test123'
>>> b = s.encode()
>>> b
b'Test123'
>>> BytesIntEncoder.encode(b)
23755444588720691
>>> BytesIntEncoder.decode(_)
b'Test123'
>>> _.decode()
'Test123'
这篇关于Python:将字母数字字符串可逆编码为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!