简体   繁体   English

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

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

I want to make an int from a string in python. 我想从python中的字符串做一个整数。 I thought to translate the string first to binary like this: 我想先将字符串转换为二进制,如下所示:

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

returns this: 返回此:

01110011 01110100 01110010 01101001 01101110 01100111

And then I want to translate the binary( in groups of 8) to integers which should to return this: 然后我想将binary(以8为一组)转换为整数,该整数应返回此值:

115 116 114 105 110 103

How can I do this? 我怎样才能做到这一点? Is there maybe a special function in python or something? python中是否可能有特殊功能?

You can use the int() function: 您可以使用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

You can simply do 你可以简单地做

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

int(str, baseNumber) will read the string str and convert it to int using baseNumber int(str, baseNumber)将读取字符串str并使用baseNumber将其转换为int

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

Why not use a bytearray ? 为什么不使用bytearray

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

Bytearray does exactly what you want -- It interprets each character in the string as an integer in the range from 0 -> 255 . Bytearray完全满足您的要求-将字符串中的每个字符解释为0255的整数。

Using the solution for binary to int here: Convert base-2 binary number string to int 在此处使用将二进制数转换为int的解决方案: 将以2为底的二进制数字符串转换为int

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

And if you just want an array of ints 如果您只想要一个整数数组

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

Addressing SpoonMeiser comments. 解决SpoonMeiser的评论。 you can avoid intermediate conversions with ord(x) 您可以避免使用ord(x)进行中间转换

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

String to binary and then to decimal : 字符串到二进制然后到十进制:

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]

## is used for outputs ##用于输出

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

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