Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading