Concise way to format list/array to custom(hex) string

K

Kurien Mathew

Hello,

What will be a concise & efficient way to convert a list/array.array of
n elements into a hex string? For e.g. given the bytes
[116, 111, 110, 103, 107, 97]
I would like the formatted string
0x74 0x6f 0x6e 0x67 0x6b 0x61

Is there an approach better than below:
hex = ''
for b in bytes:
hex += ('0x%x '%b)


Thanks
Kurien

Test program:
import array
import sys

bytes = array.array('B')
bytes.fromstring("tongka")
print bytes
hex = ''
for b in bytes:
hex += ('0x%x '%b)
print hex
 
J

John Machin

Hello,

What will be a concise & efficient way to convert a list/array.array of
n elements into a hex string? For e.g. given the bytes
[116, 111, 110, 103, 107, 97]
I would like the formatted string
0x74 0x6f 0x6e 0x67 0x6b 0x61

Is there an approach better than below:
hex = ''
for b in bytes:
hex += ('0x%x '%b)

hex = ' '.join('0x%02x' % b for b in bytes)
 
Z

Zoltán Nagy

Kurien Mathew írta:
Hello,

What will be a concise & efficient way to convert a list/array.array of
n elements into a hex string? For e.g. given the bytes
[116, 111, 110, 103, 107, 97]
I would like the formatted string
0x74 0x6f 0x6e 0x67 0x6b 0x61

Is there an approach better than below:
hex = ''
for b in bytes:
hex += ('0x%x '%b)
<snip>

You should avoid multiple string additions, as each one creates a new
string object (str objects are immutable). Try this:

bytes = [116, 111, 110, 103, 107, 97]
string = ''.join( ['0x%x '%b for b in bytes] )
 
J

josh logan

Kurien Mathew írta:
Hello,
What will be a concise & efficient way to convert a list/array.array of
n elements into a hex string? For e.g. given the bytes
[116, 111, 110, 103, 107, 97]
I would like the formatted string
0x74 0x6f 0x6e 0x67 0x6b 0x61
Is there an approach better than below:
hex = ''
for b in bytes:
    hex += ('0x%x '%b)

You should avoid multiple string additions, as each one creates a new
string object (str objects are immutable). Try this:
bytes = [116, 111, 110, 103, 107, 97]
string = ''.join( ['0x%x '%b for b in bytes] )

That results in an extra ' ' and the end of the string.  Try
this:

string = ' '.join(['0x%02x' % b for b in bytes])

There is also a built-in hex() method in the Python Standard Library.
So, to make it cleaner:
' '.join(hex(x) for x in bytes)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top