前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python标记编码 字符串转换成数字_Python:将字母数字字符串可逆编码为整数

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

作者头像
用户7886150
修改2021-01-08 10:19:01
1.7K0
修改2021-01-08 10:19:01
举报
文章被收录于专栏:bit哲学院

参考链接: Python的字符串Strings decode

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'

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档