Search code examples
pythonbytexbee

Python String to Bytes


I have to pass in a string to xbee:

xbee.tx(dest_addr='\x00\x01', data='hello world')

I'd like just to input a string or integer like 01, but then I get the message: The data provided for 'dest_addr' was not 2 bytes long

I'm using Python 2.7

How can this be resolved? Thanks.


Solution

  • You can create a simple convenience function using the struct module to convert integer addresses into the binary string format that the xbee module wants (which appears from your example to be big-endian unsigned short):

    >>> import struct
    >>> def make_address(addr):
    ...     return struct.pack(">H", addr)
    ...
    >>> make_address(1)
    '\x00\x01'