python标记编码 字符串转换成数字_Python:将字母数字字符串可逆编码为整数

I want to convert a string (composed of alphanumeric characters) into an integer and then convert this integer back into a string:

string --> int --> string

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:

string --> bytes

mBytes = m.encode("utf-8")

bytes --> int

mInt = int.from_bytes(mBytes, byteorder="big")

int --> bytes

mBytes = mInt.to_bytes(((mInt.bit_length() + 7) // 8), byteorder="big")

bytes --> string

m = mBytes.decode("utf-8")

try it out:

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')

If you're using Python <3.6, remove the optional type annotations.

Test:

>>> s = 'Test123'

>>> b = s.encode()

>>> b

b'Test123'

>>> BytesIntEncoder.encode(b)

23755444588720691

>>> BytesIntEncoder.decode(_)

b'Test123'

>>> _.decode()

'Test123'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值