Reputation: 43
This is in python. I'm new to python, but not to programming.
x = [2, 0, 0 , 0x40, 0x25, 6, 3]
I want to turn it into a string of the format
x2 = "\0x02\0x00\0x00\0x40\0x25\0x06\0x03"
The binary values from the list are in the string. I can do it with brute force, but there has to be a better way to do it.
Upvotes: 0
Views: 128
Reputation: 948
Seems simple enough...
>>> print(''.join(r'\0x'+'%02x'%i for i in x))
\0x02\0x00\0x00\0x40\0x25\0x06\0x03
Note the use of "print" - if you report the string itself, it apparently doubles up the "\" on displaying it:
>>> ''.join(r'\0x'+'%02x'%i for i in x)
'\\0x02\\0x00\\0x00\\0x40\\0x25\\0x06\\0x03'
however, the look at the characters themselves, you will see that this is a shell/display issue:
>>> x2 = ''.join(r'\0x'+'%02x'%i for i in x)
>>> print x2[0], x2[1], x2[2], x2[3], x2[4], x2[5]
\ 0 x 0 2 \
Upvotes: 1
Reputation: 43
Here is one problem... I should have had "\x02\x00\x00\x40" and so on instead of "\0x02\0x00\0x00\0x40" and so on. The problem was the "**0**x". So the wrong thing was in the string in the first place.
The brute force method is: x2 = "" for i in x x2 = x2 + chr(i)
x2 now is a string with the correct values. There should be a better way.
Upvotes: 1
Reputation: 606
Here you go
x = [2, 0, 0 , 0x40, 0x25, 6, 3]
x2 = ''
for num in x:
x2 += '\\0x{:02x}'.format(num)
>>> print(x2)
\0x02\0x00\0x00\0x40\0x25\0x06\0x03
Upvotes: 1