将数字字符串编码为缩短的字母数字字符串,然后再次返回 [英] Encoding a numeric string into a shortened alphanumeric string, and back again
问题描述
快速提问。我正在尝试在Python中查找或编写编码器,以通过使用大小写字母来缩短数字字符串。数字字符串看起来像这样:
Quick question. I'm trying to find or write an encoder in Python to shorten a string of numbers by using upper and lower case letters. The numeric strings look something like this:
20120425161608678259146181504021022591461815040210220120425161608667
长度始终相同。
我最初的想法是编写一些简单的编码器,以利用大写和小写字母和数字来缩短此字符串,使其看起来更像这样:
My initial thought was to write some simple encoder to utilize upper and lower case letters and numbers to shorten this string into something that looks more like this:
a26Dkd38JK
那是完全任意的,只是试图尽可能地清楚。
我敢肯定有一种很巧妙的方法可以做到这一点,可能已经内置了。也许这甚至是一个令人尴尬的问题。
That was completely arbitrary, just trying to be as clear as possible. I'm certain that there is a really slick way to do this, probably already built in. Maybe this is an embarrassing question to even be asking.
另外,我需要能够将缩短的字符串转换为更长的数值。
我应该编写一些东西并发布代码,还是我应该已经知道的Python函数的内置函数?
Also, I need to be able to take the shortened string and convert it back to the longer numeric value. Should I write something and post the code, or is this a one line built in function of Python that I should already know about?
谢谢!
推荐答案
这是一个很好的压缩方法:
This is a pretty good compression:
import base64
def num_to_alpha(num):
num = hex(num)[2:].rstrip("L")
if len(num) % 2:
num = "0" + num
return base64.b64encode(num.decode('hex'))
首先将整数转换为字节串,然后进行base64编码它。这是解码器:
It first turns the integer into a bytestring and then base64 encodes it. Here's the decoder:
def alpha_to_num(alpha):
num_bytes = base64.b64decode(alpha)
return int(num_bytes.encode('hex'), 16)
示例:
>>> num_to_alpha(20120425161608678259146181504021022591461815040210220120425161608667)
'vw4LUVm4Ea3fMnoTkHzNOlP6Z7eUAkHNdZjN2w=='
>>> alpha_to_num('vw4LUVm4Ea3fMnoTkHzNOlP6Z7eUAkHNdZjN2w==')
20120425161608678259146181504021022591461815040210220120425161608667
这篇关于将数字字符串编码为缩短的字母数字字符串,然后再次返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!