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.
Answer
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)
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module