0

I'm interacting with an XBEE RF chip and want to decode it's incoming source address from a byte array to a string. The manufacturer's software does this already but I need to handle this in my own custom program. So

Received Address: b'\x00\x13\xa2\x00Aga\xf8'

Address (Decoded by Manufacturer): 00 13 A2 00 41 67 61 F8

I have been trying to decode this using address.decode('utf-8') but always receive a UnicodeDecodeError at \xa2 as an invalid start byte. I also need to know how to convert from the decoded version back to the byte array for sending messages back down the network.

Thanks in advance

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
Phillip McMullen
  • 453
  • 2
  • 5
  • 15

1 Answers1

2

On Python 3.5 and higher, bytes (and some other bytes-like types) have a hex method, so you can just do:

b'\x00\x13\xa2\x00Aga\xf8'.hex()

to get:

'0013a200416761f8'

You can call .upper() on the result if case is important.

On 3.4 and earlier, import binascii, then use the hexlify function:

binascii.hexlify(b'\x00\x13\xa2\x00Aga\xf8')

to get the same result.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • Thank you!! This worked perfect. For anyone else that follows this, to return from the hex format to the original bytes, I used bytes.fromhex(hex_output) – Phillip McMullen Jan 17 '18 at 17:00