I'm new in Python and need to convert an array of integers into one in binary code.
s_str = "test"
s_acii = [ord(c) for c in s_str]
print(s_acii)
>> [116, 101, 115, 116]
What I need:
>> [1110100, 1100101, 1110011, 1110100]
Thanks!
I'm new in Python and need to convert an array of integers into one in binary code.
s_str = "test"
s_acii = [ord(c) for c in s_str]
print(s_acii)
>> [116, 101, 115, 116]
What I need:
>> [1110100, 1100101, 1110011, 1110100]
Thanks!
You can use bin
built-in function to convert the integers into their binary representations:
>>> l = [116, 101, 115, 116]
>>> [bin(i) for i in l]
['0b1110100', '0b1100101', '0b1110011', '0b1110100']
If you do not want the 0b
prefix, use string formatting with binary integer representation:
>>> l = [116, 101, 115, 116]
>>> ["{0:b}".format(i) for i in l]
['1110100', '1100101', '1110011', '1110100']
You can use the str.format
method with b
as the presentation type:
print('[{}]'.format(', '.join(map('{:b}'.format, s_acii))))
This outputs:
[1110100, 1100101, 1110011, 1110100]