Convert an integer to a 2 byte Hex value in Python

Brett Prudhom picture Brett Prudhom · May 24, 2013 · Viewed 22.2k times · Source

For a tkinter GUI, I must read in a Hex address in the form of '0x00' to set an I2C address. The way I am currently doing it is by reading the input as a string, converting the string to an integer, then converting that integer to an actual Hex value as shown in the partial code below:

GUI initialization:

self.I2CAddress=StringVar()
self.I2CAddress.set("0x00") #Sets Default value of '0x00'
Label(frame, text="Address: ").grid(row=5, column=4)
Entry(frame, textvariable=self.I2CAddress).grid(row=5, column=5)

Then inside the function:

addr = self.I2CAddress.get()   
addrint = int(addr, 16)  
addrhex = hex(addrint)

This works for most values, but my issue is that if I enter a small Hex value string such as '0x01', it converts to the proper integer of 1, but then that is converted to a Hex value of 0x1 instead of 0x01.

I am an EE and have very limited programming experience, so any help is greatly appreciated.

Answer

Martijn Pieters picture Martijn Pieters · May 24, 2013

Use the format() function:

format(addrint, '#04x')

This formats the input value as a 2 digit hexadecimal string with leading zeros to make up the length, and # includes the 'standard prefix', 0x in this case. Note that the width of 4 includes that prefix. x produces lower-case hex strings; use X if you need uppercase.

Demo:

>>> for i in range(8, 12):
...     print format(i, '#04x')
... 
0x08
0x09
0x0a
0x0b