Python convert array of strings to array of bytes

Viewed 65

I am trying to convert an array of strings oldlist = ['00000100', '10100001', '11000001', '11100001'] that are binary values into bytes of their value as hex codes so the resulting list would look like this newlist = [b'\x04', b'\xa1', b'\xc1', b'\xe1']. I get the basic concept of looping through the first list and appended to the previous or doing some sort of list comp. But I can't find a function to convert "00000100" to " b'\x04' "

3 Answers

You can use int(number, 2) to convert the string to integer:

oldlist = ["00000100", "10100001", "11000001", "11100001"]

out = list(map(lambda x: bytes([int(x, 2)]), oldlist))
print(out)

Prints:

[b'\x04', b'\xa1', b'\xc1', b'\xe1']

what you can do is to use string.getBytes();

You first need to convert the binary string to an integer. For this you can use int() method with radix of 2. Then to convert that to bytes, use the bytes() method like this bytes([x]).

>>> oldlist = ['00000100', '10100001', '11000001', '11100001']
>>> list(map(lambda x: bytes([int(x, 2)]), oldlist))
[b'\x04', b'\xa1', b'\xc1', b'\xe1']
Related