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

Lexy Zhitenev zhitenev at cs.vsu.ru
Tue Nov 26 11:41:38 EST 2002


 > Example:
>
> number         =    6673            (max is 0xFFF)

I think max is 0xFFFF

> 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")
>

This is not the most elegant and the fastest solution, but it's one of the
simplest I think.

>>> import operator

>>> conv_num = lambda r: reduce(operator.add, map(lambda x:
'\\x'+hex(ord(x))[2:], hex(r)[2:].zfill(4)))
>>> print conv_num(333)
\x30\x31\x34\x64

Look into library reference for ord, lambda, map and reduce.

hex(r)[2:].zfill(4) - make a string as a hex number
hex(ord(x))[1:] - '0' -> '0x30' -> 'x30'
map applies the above function consequently to all items of the string as a
hex number
reduce(operator.add, xxx) turns the list of 'map' results back to string.

operator.add = lambda x,y: x+y, only faster.

Good Luck!





More information about the Python-list mailing list