Search code examples
pythontypesbinaryspi

Convert binary string to a binary integer in Python


I want to send binary data via SPI, so I structured my code as constants of binary strings, representing various commands and registers on the SPI device.

RD = '01'
WR = '10'

MDR0 = '001'
MDR1 = '010'

so for example, if I want to write to MDR0 I add both strings and format them with a constant length:

msg = WR + MDR0
msg = int(msg, 2)

msg = [format(msg, '#010b')]
print(msg)
>> ['0b00010001']

My problem is, now msg has a str data not an int so it can't be sent using spidev package.

bin(int(msg[0],2))

The above code results in a string data type as well! How can I have this binary string as a binary integer where I might as well do binary operations on it?


Solution

  • Make integer bit masks. OR the bits to make IR register values:

    import spidev
    
    RD = 0b01 << 6  # bits 6-7
    WR = 0b10 << 6
    
    MDR0 = 0b001 << 3  # bits 3-5
    MDR1 = 0b010 << 3
    
    spi = spidev.SpiDev()
    spi.open(bus, device)
    msg = [WR | MDR0]
    spi.xfer(msg)