Hello guys

I want to convert an integer to a hexadecimal string
examples
lets say i have an integer value 1 i want to convert it to 0001
integer value of 16 => 0010
245 =>00F5
and so on the string must have a length of 4 digits
my code is like this but i was wondering if there is an another way to do it

new_address=hex(new_address)[2:].upper()
                if len(new_address)==3:
                    new_address="0"+new_address
                elif len(new_address)==2:
                    new_address="00"+new_address
                elif len(new_address)==1:
                    new_address="000"+new_address
                print new_address

I want to convert an integer to a hexadecimal string
examples
lets say i have an integer value 1 i want to convert it to 0001
integer value of 16 => 0010
245 =>00F5
and so on the string must have a length of 4 digits

It will be way simpler to use string formatting like so:

>>> print '%04X' % 16
0010
>>> print '%04X' % 245
00F5
>>> print '%04X' % 1024
0400
>>> print '%04X' % 4096
1000

I'm sure you know already how to use the % symbol in strings to substitute values; however you may only know the basic usage. In this particular example we use a number of properties. First, the 0 denotes that we want our string to be padded with zeroes. Then we have a 4, which indicates we're reserving 4 spaces (if we simply had a 4 without the 0 there would be a blank space instead of a zero). And then finally we have the X. This indicates we're formatting the input (in this case an integer) to print out in hexadecimal. If we had used a lower-case X (ie, x) then the output would use lower-case hexadecimal digits.

HTH

Edited 7 Years Ago by jlm699: Added explanation

Well jlm699 thank you !!!
your solution it was great
its similar to C syntax ...
and its only one line

new_address="%04X" % new_address
This article has been dead for over six months. Start a new discussion instead.