Skip to content
Advertisement

Convert int to hex and make terminal read it as hex

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 += "xdaxc7xd9x74x24xf4xbex9dxcax88xfbx5ax29"
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??

Advertisement

Answer

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().

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement