I want to make an int from a string in 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:
115 116 114 105 110 103
How can I do this? Is there maybe a special function in python or something?
-
1This is probably what you need: stackoverflow.com/a/8928256/5712767WreckeR– WreckeR2016年04月26日 16:22:14 +00:00Commented Apr 26, 2016 at 16:22
-
indeed, sorry, I've edited itsvs– svs2016年04月26日 16:37:47 +00:00Commented Apr 26, 2016 at 16:37
5 Answers 5
You can use the int() function:
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
Comments
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
so int("0xFF", 16) = 255 and int("11", 2) = 3
Comments
Using the solution for binary to int here: Convert base-2 binary number string to 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. you can avoid intermediate conversions with ord(x)
int_array = [ord(x) for x in st]
3 Comments
ord(x)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