Python - Convert List of Integers to a bit-mapped byte


#1

I have a list of integers that represents solenoid numbers to turn ON ,e.g.
[1, 3, 4, 7], where number “1” represents the 1st solenoid, "3 the 3rd solenoid etc,
so this list means turn solenoids 1, 3, 4 and 7 ON, all the others OFF.

I need to output this as a bit-mapped byte where each bit (0 to 7) represents solenoids 1 to 8 respectively.
So for the above case this would look like the following bit-mapped byte 01001101 in binary.

Is there a Python library that will handle this for me, or does anyone have a code snippet that they can share please?

Thanks,
Eric


#2

Numerically we know that bit 8 is128, bit 7 is 64, and so on. In other words, 2 ** (n.- 1) where n is 1…8.

So [1, 3, 4, 7] will be,

[2 ** 0, 2 ** 2, 2 ** 3, 2 ** 6]

If we reverse the list we get the high order bit on the left.

64 + 8 + 4 + 1  ==  77

The sum of the orders that are not turned on is,

255 - 77  ==  178

We can use the difference as an exclusive or operand to set the opposite bits.

>>> bin(255 ^ 178)
'0b1001101'
>>> bin(255 ^ 77)
'0b10110010'
>>> 

There are no leading zeros in integers so if one is needed as a placeholder, the binary string will need to be manipulated.

>>> on = bin(255 ^ 178)
>>> on = on[:2] + '0' + on[2:]
>>> on
'0b01001101'
>>> 

In other words,

>>> on = bin(255 ^ 240)
>>> while len(on) < 10:
    on = on[:2] + '0' + on[2:]

    
>>> on
'0b00001111'
>>> 

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.