Jones
Jones

Reputation: 1500

Convert Hexa array to String

I need convert this array

data = [
#SHO
0x56, 0x0d, 
#CMD
0x1, 0x00, 0x00, 0x00, 
#ARG
0x1, 0x0,
#SIZE
0x02, 0x00, 0x00, 0x00, 
#OPAQUE
0x01, 0x02,
#RESERVED
0x00, 0x00
]

and produce a string

# converted data into s
print s

Upvotes: 1

Views: 501

Answers (3)

Levon
Levon

Reputation: 143122

In [16]: ''.join(str(i) for i in data)
Out[16]: '861310001020001200'

or (as perhaps as per @thg435's suggestion) using chr() in place of str():

In [25]: ''.join(chr(i) for i in data)
Out[25]: 'V\r\x01\x00\x00\x00\x01\x00\x02\x00\x00\x00\x01\x02\x00\x00'

Is this what you are looking for? If not, can you provide the desired output?

Upvotes: 3

Maria Zverina
Maria Zverina

Reputation: 11173

Do you mean to read it as string of bytes?

print bytearray(data)

Upvotes: 4

Claudiu
Claudiu

Reputation: 229491

(Combining the current posts since the question is ambiguous.)

Printing the bytes in hex:

>>> ''.join(('%2s' % hex(d)[2:]).replace(' ', '0') for d in data)
'560d0100000001000200000001020000'

Printing the bytes as decimal:

>>> ''.join(str(i) for i in data)
'861310001020001200'

Printing the bytes as characters:

>>> print bytearray(data)
☺   ☺ ☻   ☺☻

or equivalently:

>>> print ''.join(map(chr, data))
☺   ☺ ☻   ☺☻

Upvotes: 0

Related Questions