这是我到目前为止所拥有的:
字符串 --> 字节
mBytes = m.encode("utf-8")
Run Code Online (Sandbox Code Playgroud)
字节 --> 整数
mInt = int.from_bytes(mBytes, byteorder="big")
Run Code Online (Sandbox Code Playgroud)
int --> 字节
mBytes = mInt.to_bytes(((mInt.bit_length() + 7) // 8), byteorder="big")
Run Code Online (Sandbox Code Playgroud)
字节 --> 字符串
m = mBytes.decode("utf-8")
Run Code Online (Sandbox Code Playgroud)
试试看:
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)
Run Code Online (Sandbox Code Playgroud)
这是上述内容的相同可重用版本:
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')
Run Code Online (Sandbox Code Playgroud)
如果您使用的是 Python <3.6,请删除可选的类型注释。
测试:
>>> s = 'Test123'
>>> b = s.encode()
>>> b
b'Test123'
>>> BytesIntEncoder.encode(b)
23755444588720691
>>> BytesIntEncoder.decode(_)
b'Test123'
>>> _.decode()
'Test123'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6316 次 |
| 最近记录: |