views:

1001

answers:

4

I want to take an integer (that will be <= 255), to a hex string representation

eg: I want to pass in 65 and get out '\x65', or 255 and get '\xff'

I've tried doing this with the struct.pack('c', 65), but that chokes on anything above 9 since it wants to take in a single character string.

Thanks,

+4  A: 

You are looking for the chr function.

You seem to be mixing decimal representations of integers and hex representations of integers, so it's not entirely clear what you need. Based on the description you gave, I think one of these snippets shows what you want.

>>> chr(0x65) == '\x65'
True


>>> hex(65)
'0x41'
>>> chr(65) == '\x41'
True

Note that this is quite different from a string containing an integer as hex. If that is what you want, use the hex builtin.

Mike Graham
Exactly what I was looking for. Thanks, couldnt find that function for the life of me and knew there had to be something cleaner than using hex and doing replace on it.
pynoob
So where is the answer approval?
Dejw
A: 

Try:

"0x%x" % 255 # => 0xff

or

"0x%X" % 255 # => 0xFF

Python Documentation says: "keep this under Your pillow: http://docs.python.org/library/index.html"

Dejw
A: 

What about hex()?

hex(255)  # 0xff

If you really want to have \ in front you can do:

print '\\' + hex(255)[1:]
Felix Kling
+1  A: 

This will convert an integer to a 2 digit hex string with the 0x prefix:

strHex = "0x%0.2X" % 255
Greg Bray
Have You read my answer?
Dejw