I want to take an integer (that will be <= 255), to a hex string representation
e.g.: I want to pass in 65
and get out \'\\x41\'
, or
This will convert an integer to a 2 digit hex string with the 0x prefix:
strHex = "0x%0.2X" % 255
What about hex()?
hex(255) # 0xff
If you really want to have \
in front you can do:
print '\\' + hex(255)[1:]
I wanted a random integer converted into a six-digit hex string with a # at the beginning. To get this I used
"#%6x" % random.randint(0xFFFFFF)
As an alternative representation you could use
[in] '%s' % hex(15)
[out]'0xf'
If you want to pack a struct with a value <255 (one byte unsigned, uint8_t) and end up with a string of one character, you're probably looking for the format B instead of c. C converts a character to a string (not too useful by itself) while B converts an integer.
struct.pack('B', 65)
(And yes, 65 is \x41, not \x65.)
The struct class will also conveniently handle endianness for communication or other uses.
With format()
, as per format-examples, we can do:
>>> # format also supports binary numbers
>>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
'int: 42; hex: 2a; oct: 52; bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'