Shai
Shai

Reputation: 55

Python - Printing Hex from a file

I have the following code:

code1 = ("\xd9\xf6\xd9\x74\x24\xf4\x5f\x29\xc9\xbd\x69\xd1\xbb\x18\xb1")
print code1

code2 = open("code.txt", 'rb').read()
print code2

code1 output:

�צ�t$פ_)�½i�»±

code2 output:

"\xd9\xf6\xd9\x74\x24\xf4\x5f\x29\xc9\xbd\x69\xd1\xbb\x18\xb1"

I need code2 (which I read from a file) to have the same output as code1.
How can i solve this ?

Upvotes: 1

Views: 2601

Answers (3)

unutbu
unutbu

Reputation: 880747

To interpret a sequence of characters such as

In [125]: list(code2[:8])
Out[125]: ['\\', 'x', 'd', '9', '\\', 'x', 'f', '6']

as Python would a string with escaped characters, such as

In [132]: list('\xd9\xf6')
Out[132]: ['\xd9', '\xf6']

use .decode('string_escape'):

In [122]: code2.decode('string_escape')
Out[122]: '\xd9\xf6\xd9t$\xf4_)\xc9\xbdi\xd1\xbb\x18\xb1'

In Python3, the string_escape codec has been removed, so the equivalent becomes

import codecs
codecs.escape_decode(code2)[0]

Upvotes: 5

tomasz
tomasz

Reputation: 13072

This example:

import binascii

code1 = "\xd9\xf6\xd9\x74\x24\xf4\x5f\x29\xc9\xbd\x69\xd1\xbb\x18\xb1"
code2 = "\\xd9\\xf6\\xd9\\x74\\x24\\xf4\\x5f\\x29\\xc9\\xbd\\x69\\xd1\\xbb\\x18\\xb1"

print code1 == binascii.unhexlify(code2.replace('\\x', ''))

prints True.

You can use binascii.unhexlify to convert hexadecimal text representation to binary, but first have to remove \x from the string.

EDIT: I've just realised that double quotes are part of your output. Essentially you need to pass just valid hex string, so everything else need to be stripped off. In your case you need to pass code2.replace('\\x', '').strip('"') to unhexlify. You can use eval and probably will, but consider this Security of Python's eval() on untrusted strings? for future choices.

Upvotes: 3

ngn
ngn

Reputation: 7902

print eval(code2) should do the job.

Upvotes: -3

Related Questions