Skip to main content
 首页 » 编程设计

python之字符串(到二进制)到 python 中的 int

2025年05月04日20mfryf

我想在 python 中从一个字符串生成一个 int。我想像这样先将字符串翻译成二进制:

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

返回这个:

01110011 01110100 01110010 01101001 01101110 01100111 

然后我想将二进制(以 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