Converting From a list of bits to a byte array

905 views Asked by At

I am really struggling here as a new programming with a process using the snap7 library connected to a siemens PLC using Python3 on a raspberry PI. Basically I am reading in data as a byte array then modifying it and sending it back to the PLC. I am able to read it in and convert it to a list and modify the data.

So my data is a list that looks like [0,0,0,0,0,0,1,0]. It will always be exactly 1 byte (8 bits). So I can modify these bits. However I am struggling with getting them back into a byte array. I need to convert from that list into a byte array response that should look like bytearray(b'\x02')

Couple examples of what I am expecting

Input [0,0,0,0,0,0,0,1]
Output bytearray(b'\x01')

Input [0,0,0,0,0,0,1,0]
Output bytearray(b'\x02')

Input[0,0,0,0,0,0,1,1]
Output bytearray(b'\x03')

It is a bit odd that it is a byte array for only 1 byte but that is how the library works for writing to the datablock in the PLC.

Please let me know if there is any additional data I can share Kevin

1

There are 1 answers

1
kinshukdua On BEST ANSWER

First convert the list to a decimal, this can be done in one line using.

sum(val*(2**idx) for idx, val in enumerate(reversed(binary)))

but to make the code a little more readable

binary_list = [0,0,0,0,0,0,1,0]
number = 0
for b in binary_list:
    number = (2 * number) + b

Then simply use bytearray and add the number as an input

output = bytearray([number])

Changing this into a function

def create_bytearray(binary_list):
    number = 0
    for b in binary_list:
        number = (2 * number) + b
    return bytearray([number])

Now you just have to call

output = create_bytearray([0,0,0,0,0,0,1,0])
print(output)

And you will get

bytearray(b'\x02')