tags:

views:

949

answers:

1

I have a string that has both binary and string characters and I would like to convert it to binary first, then to hex.

The string is as below:

<81>^Q<81>"^Q^@^[)^G ^Q^A^S^A^V^@<83>^Cd<80><99>}^@N^@^@^A^@^@^@^@^@^@^@j

How do I go about converting this string in Python so that the output in hex format is similar to this below?

24208040901811001B12050809081223431235113245422F0A23000000000000000000001F
+5  A: 

You can use ord and hex like this :

>>> s = 'some string'
>>> hex_chars = map(hex,map(ord,s))
>>> print hex_chars
['0x73', '0x6f', '0x6d', '0x65', '0x20', '0x73', '0x74', '0x72', '0x69', '0x6e', '0x67']
>>> hex_string = "".join(c[2:4] for c in hex_chars)
>>> print hex_string
736f6d6520737472696e67
>>>

Or use the builtin encoding :

>>> s = 'some string'
>>> print s.encode('hex_codec')
736f6d6520737472696e67
>>>
Ferran