2

I am trying to convert an integer to hex. I have found answers that address this problem like this, though they do not work for me. What i mean:

if i take this:

buf =  ""
buf += "\xda\xc7\xd9\x74\x24\xf4\xbe\x9d\xca\x88\xfb\x5a\x29"
print buf

and i run it from console with python myfile.py then the output is something like this: ���t$���ʈ�Z), which is what i want (the output has been read as hex). If though i try this:

var1 = 230
var2 = ""
var2 = "\\" + "x" + "%0.2X" % var1 
print var2

the output is \xE6, not read as hex by the console. What am i missing here??

Community
  • 1
  • 1
J.S
  • 147
  • 1
  • 3
  • 12

2 Answers2

3

\xda is an escape sequence that is interpreted by the Python interpreter. \ has no meaning by itself, and \\ is an escape sequence meaning "backslash".

To convert custom hex numbers to text, see this question: Convert from ASCII string encoded in Hex to plain ASCII?. Here is a summary of the simplest answer: ("%0.2X" % var1).decode("hex").

Community
  • 1
  • 1
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
2

In the first example what you're doing is creating a sequence of escape characters. So when the code has

buf = "\xc9"

The interpreter is actually converting that to a character encoded by 0xc9 in ascii.

The problem you're having is that your code doesn't allow for these conversions. Your code ask for a string that is just the character \ then x followed by the hex value of some variable.

What you are probably looking for is something like this:

var = 230
buf = ""
buf += chr (var1)

NOTE: if you need to encode UTF-8 values (basically anything greater than 255 you may want to use unichr() rather than chr().

Josh Kergan
  • 335
  • 3
  • 9