How to convert ASCII-number => HEX -number => string of numbers in HEX ?

Padraig Brady Padraig at Linux.ie
Tue Nov 26 11:39:34 EST 2002


Pekka Niiranen wrote:
> Hi,
> 
> I looked thru modules binascii and struct but not found a way to
> convert hexadecimal value to a string of hex values according to ascii 
> table.
> 
> Example:
> 
> number         =    6673            (max is 0xFFF)
> hex -value     =    '0x1a11'
> string value    =    "\x31\x61\x31\x31"    (31 is one, 61 is 'a')
> 
> or:
> 
> number         =    333            (max is 0xFFF)
> hex -value     =    '0x14d'   string value    =    "\x30\x31\x34\x64"    
> (30 is zero, 31 is one, 34 is four, 64 is "d")
> 
> I have got this far:
> 
> x=""
> a = hex(333)
> for byte in a[2:].zfill(4):        # Number is allways presented with 4 
> hex values (filling missing values with zeros)
>    x = "%s%s" % ( WHAT HERE )
> 
> Anybody, is there a build in function or shortcut  that does this ?

x=''
for byte in string.zfill(hex(6673)[2:],4):
     x=x+ r'\x%02x' % ord(byte)

Hmm ''.zfill() isn't present on python 2.2 at least?
(string.zfill() is?)

Pádraig.




More information about the Python-list mailing list