Nathan Bush
Nathan Bush

Reputation: 1461

Adding single backslash to binary string in python

Am communicating with a piece of equipment over RS232, and it seems to only interpret commands correctly when issued commands in the following format:

b'\xXX'

for example:

equipment_ser.write(b'\xE1')

The argument is variable, and so I convert to hex before formatting the command. I'm having trouble coming up with a consistent way to ensure only 1 backslash while preserving the hex command. I need the entire range - \x00 to \xFF.

One approach was to use 'unicode escape':

    setpoint_command_INT = 1

    setpoint_command_HEX = "{0:#0{1}x}".format(setpoint_command_INT,4)
    
    setpoint_command_HEX_partially_formatted = r'\x' + setpoint_command_HEX[2:4]

    setpoint_command_HEX_fully_formatted = setpoint_command_HEX_partially_formatted.encode('utf_8').decode('unicode_escape')

works ok for the above example:

Out[324]: '\x01'

but not for large numbers where the code process changes it:

setpoint_command_INT = 240

Out[332]: 'ð'

How can I format this command so that I have the single backslash while preserving the ability to command across the full range 0-255?

Thanks

Edit:

The correct way to do this is as said by Michael below:

bytes((240,))

Thank you for the prompt responses.

Upvotes: 0

Views: 484

Answers (1)

Adon Bilivit
Adon Bilivit

Reputation: 27404

In your code, you are sending a single byte

equipment_ser.write(b'\xE1')

In other words, you're sending decimal 225 but as a single byte.

For any integer value in the range 0-255 you can create its byte equivalent by:

import sys
N = 225 # for example
b = N.to_bytes(1, sys.byteorder)
equipment_ser.write(b)

Upvotes: 1

Related Questions