簡體   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