Aug-25-2020, 03:23 AM
(Aug-25-2020, 03:00 AM)Peter_Truman Wrote: If I went with
bits = [1 if x == "1" else 0 for x in f"{result:08b}"[-8:]] # takes only 8 LSB in case result > 2**8Would that not simply leave me with a string called 'bits' - so effectively just masking out the lower 4 bits of result?
No, it's just compact. The first part (the f-string) converts the byte to the 8 LSB bits as a string object.
f"{result:08b}"[-8:]
The next part goes through each character of the string one-by-one and converts it to a list of numbers, either 0 or 1. So the MSB is index 0 and the LSB is index 7, via a list comprehension. Expanding the loop, it would look like:
temp_list = [] for x in f"{result:08b}"[-8:]: if x == "1": temp_list.append(1) else: temp_list.append(0) bits = temp_listSo at the end, you've got the list
[1, 1, 1, 0, 0, 1, 1, 1]
It looks like there's also a PyPi module called bitstring. It could be that it has some functions that would be useful.