/ / Python String to Bytes: python, byte, xbee

Python String to Bytes: python, byte, xbee

Devo passare una stringa a xbee:

xbee.tx(dest_addr="x00x01", data="hello world")

Mi piacerebbe solo inserire una stringa o un intero come 01, ma poi ottengo il messaggio: The data provided for "dest_addr" was not 2 bytes long

Sto usando Python 2.7

Come può essere risolto? Grazie.

risposte:

2 per risposta № 1

Puoi creare una semplice funzione di convenienza usando il struct modulo per convertire gli indirizzi integer nel formato di stringa binario che vuole il modulo xbee (che appare dal tuo esempio come short-endian senza firma):

>>> import struct
>>> def make_address(addr):
...     return struct.pack(">H", addr)
...
>>> make_address(1)
"x00x01"