繁体   English   中英

将整个 ascii 字符串转换为 int

[英]Convert whole ascii string into a int

我正在寻找将像“ASDF”这样的字符串转换成一个像“123456789”这样可以很容易地转换回“ASDF”的数字,我 go 如何在 python 3 中执行此操作?

您可以使用ord将每个字符转换为其 ascii 值,并使用f"{1:02d}"将它们格式化为相同的长度并将它们连接在一起。 然后,当您想要字符串返回时,请反转此过程。

就像是

def to_num(s):
    return int("1" + "".join(map(lambda a: f"{ord(a):03d}", s)))

def to_str(n):
    num = str(n)[1:]
    chunks = [num[i:i+3] for i in range(0, len(num), 3)]
    return "".join(map(lambda a: chr(int(a)), chunks))

那个怎么样:

int.from_bytes("ASDF".encode('utf-8'), byteorder='big', signed=False)
1095976006

然后回来

import math
(1095976006).to_bytes(math.ceil((1095976006).bit_length() / 8), byteorder = 'big', signed=False).decode('utf-8')
'ASDF'

它使用编码/解码将 Python 字符串的 utf-8 表示形式作为字节数组,然后使用 from_bytes/to_bytes 将其转换为 integer。因此它适用于任何字符串。 令人惊讶的是,必须计算字节数才能使用 to_bytes。

只是想出了一个可能的方法,因为我只使用 ASCII,所以这应该有效:

inp = "ASDF" #Input string
bits = 8     #Amount of bits per character

num = 0      #Just some setup value, this will be our encoded number
numstr = [ord(letter) for letter in inp] #Turns the string into a list containing each of the letters ascii code
for numletter in numstr: #Loop over each letter
    num = (num<<bits)+numletter #First shift the current num stored by 8 [In binary 01010101 becomes 0101010100000000] which makes room for the next character, then adds the new character in

print("Encoded:",num) #Print the encoded number

#num = 1234, not included as we've defined it before with the encoding part
#bits = 8, same reason as above
outp = "" #Another setup value, this will be our decoded string
AND = ((2**bits)-1) #A setup constant, we'll need this later, this is a number of just 1's in binary with the length of 8.
while num>=1: #Loop over each character
     numletter = num&AND #Bitwise AND it with the constant we got earlier, this'll extract the first character in the number
     outp = chr(numletter) + outp #First convert the extracted number to it's character, then add the character to the front of the output
     num = num>>bits #Remove the extracted number and shift it back by 8

print(outp) #Print the decoded string

根据定义有点问题。 根据字符串的长度,您很容易用完整数。 除非你指的是字符串表示中的数字,否则理论上是可能的,但实际上你将需要将这些 int 作为字符串数字来处理的算术。 基本上,如果您仅限于 ascii,请使用 base 26 表示:

"F"*26^0 + "D"*26^1 + "S" * 26^ 2 and so on

或者你可以只连接字符代码,这也是一个选项,虽然它看起来毫无意义 - 你并没有真正将字符串转换为数字,你只是以另一种方式打印它的表示。

或者,您可能正在谈论将封闭的字符串集映射到整数 - 然后只需将您的字符串放入列表中并使用它们的索引作为匹配的 int。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM