Python Forum

Full Version: UART write binary code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hello,

I am trying to send out a binary code with the UART.
with a hexadecimal code it works:
command = b'\x80'
scanner_uart.write(command)
but how can I send out a binary code?
e.g. 00001111
thank you.
b'\x80' is just a representation of hexadecimal code and is equivalent to 01000000 binary
so 00001111 would be b'\x0f'

Please show enough code so that condition can be recreated.
Please post all errors
You could try this (perhaps not the most efficient)
>>> bytes([int('00001111', 2)])
b'\x0f'
>>> int('00001111', 2).to_bytes(1, 'little')
b'\x0f'
What do you mean by "send binary code"? Do you want to send a binary string (bytes 30 and 31)? That would be b'00001111' or bytes((30, 30, 30, 30, 31, 31, 31, 31)).

Do you want to send 15? That would be bytes((15)) or b'\08'. There is no escape sequence for binary digits like there is for hexadecimal digits.

Do you have a binary string that you want to convert to bytes? Gribouillis covers that in his post. I would not do this for literals in the program, but if you have entered strings that need to be converted, it will do the trick.