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
Last edited by jlm699; Oct 26th, 2009 at 9:46 am. Reason: Added explanation
Reputation Points: 355
Solved Threads: 292
Veteran Poster
Offline 1,102 posts
since Jul 2008