jorrebor
jorrebor

Reputation: 2232

how to return [0x01, 0xFF,.....] as string ''01 FF ....' in python

I'm confused about this. how to print hexadecimal bytes:

 [0x05, 0x06, 0x40, 0xFD, 0x05]

as this in the console:

 05 06 40 FD 05    

And how would I use this in a to_string function:

def to_string(bytes):
    cmd = '%02X'.join(chr(b) for b in self.bytes) #does not work obviously
    return cmd

print to_string([0x05, 0x06, 0x40, 0xFD, 0x05])

I thought I could generalize from your answer.

Upvotes: 2

Views: 3972

Answers (2)

monkut
monkut

Reputation: 43860

Martijn's answer is the right answer, but here are some related functions you may not be familiar with.

With the python format string operator:

>>> for i in [0x05, 0x06, 0x40, 0xFD, 0x05]:
...     print "{:02X}".format(i),
...
05 06 40 FD 05

If you actually had the data as bytestrings you could use binascii.hexlify to do the same.

>>> import binascii
>>> data = ["\x05", "\x06", "\x40", "\xFD", "\x05"]
>>> for d in data:
...     print binascii.hexlify(d),
...
05 06 40 fd 05

You could also use the builtin hex() with your existing data if you don't mind the data not being padded.

>>> data = [0x05, 0x06, 0x40, 0xFD, 0x05]
>>> for i in data:
...     print hex(i),
...
0x5 0x6 0x40 0xfd 0x5
>>>
>>>
>>> # Or use the slice operator to cut off the initial "0x"
>>> for i in data:
...     print hex(i)[2:],
...
5 6 40 fd 5

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1123400

Use the %02X string formatter:

>>> print '%02X' % 0x05
05
>>> for i in [0x05, 0x06, 0x40, 0xFD, 0x05]:
...     print '%02X' % i,
...
05 06 40 FD 05

or to make it one string:

>>> ' '.join(['%02X' % i for i in [0x05, 0x06, 0x40, 0xFD, 0x05]])
'05 06 40 FD 05'

Upvotes: 7

Related Questions