簡體   English   中英

字符串(二進制)到int in python?

[英]string (to binary) to int in python?

我想從python中的字符串做一個整數。 我想先將字符串轉換為二進制,如下所示:

st = 'string'
binSt = ' '.join(format(ord(x), '08b') for x in st)

返回此:

01110011 01110100 01110010 01101001 01101110 01100111

然后我想將binary(以8為一組)轉換為整數,該整數應返回此值:

115 116 114 105 110 103

我怎樣才能做到這一點? python中是否可能有特殊功能?

您可以使用int()函數:

result = ''
st = 'string'
binSt = ' '.join(format(ord(x), '08b') for x in st)
binSt_split = binSt.split()
for split in binSt_split:
    result = result + str(int(split,2) + ' '
print result

你可以簡單地做

r = [int(numbs, 2) for numbs in binSt.split(' ')]

int(str, baseNumber)將讀取字符串str並使用baseNumber將其轉換為int

所以int("0xFF", 16) = 255int("11", 2) = 3

為什么不使用bytearray

>>> barr = bytearray('string')
>>> barr[0]
115

Bytearray完全滿足您的要求-將字符串中的每個字符解釋為0255的整數。

在此處使用將二進制數轉換為int的解決方案: 將以2為底的二進制數字符串轉換為int

 binSt = ' '.join([str(int(format(ord(x), '08b'), 2)) for x in st])

如果您只想要一個整數數組

 int_array = [int(format(ord(x), '08b'), 2) for x in st]

解決SpoonMeiser的評論。 您可以避免使用ord(x)進行中間轉換

 int_array = [ord(x) for x in st]

字符串到二進制然后到十進制:

st = 'string'
binSt = ' '.join(format(ord(x), '08b') for x in st)
binSt
##'01110011 01110100 01110010 01101001 01101110 01100111'
bin=binSt.split()
bin
##['01110011', '01110100', '01110010', '01101001', '01101110', '01100111']
print(map(lambda x: int(x,2), bin))
##[115, 116, 114, 105, 110, 103]

##用於輸出

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM