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

Bengt Richter bokr at oz.net
Tue Nov 26 14:04:17 EST 2002


On Tue, 26 Nov 2002 18:09:23 +0200, Pekka Niiranen <krissepu at vip.fi> 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.
>
I suspect you are working too hard ;-)

>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 ?
>
There are other % formatting options than %s.
Perhaps this is what you want?

>>> number = 6673
>>> '%04x' % number
'1a11'
>>> '%04X' % number
'1A11'
>>> number = 333
>>> '%04x' % number
'014d'
>>> '%04X' % number
'014D'

IMO section 7.1 of the tutorial ought to have a link
where it mentions % formatting. Here is where that is
discussed in some (fairly terse) detail:

http://www.python.org/doc/current/lib/typesseq-strings.html

If you are familiar with C [s]printf formatting, it's virtually
the same. In fact, you can define your own printf-like function with

 >>> import sys
 >>> def printf(fmt, *args):
 ...     sys.stdout.write(fmt % args)
 ...

Then you can write

 >>> printf('%5d: %04x %04X %X\n', 333, 333, 333, 333)
   333: 014d 014D 14D

(Note that there is a comma after the format string, followed not
by '%' but by a comma and the rest of the arguments. The '*' on the
args in the def collects a variable number of args into a single tuple
named (in this case) args).

Using a Python print statement, you'd write

 >>> print '%5d: %04x %04X %X' % (333, 333, 333, 333)
   333: 014d 014D 14D

to get the same output. (Note the '\n' supplied by print but not sys.stdout.write)

Regards,
Bengt Richter



More information about the Python-list mailing list