Help needed with translating perl to python

attn.steven.kuo at gmail.com attn.steven.kuo at gmail.com
Tue Jun 26 13:22:16 EDT 2007


On Jun 26, 8:59 am, attn.steven.... at gmail.com wrote:

(snipped)

>
> >>> def bcdlen(*args):
>
> ...     strlen = "%04s" % str(args[0])
> ...     firstval = int(strlen[2:3]) * 16 + int(strlen[3:4])
> ...     lastval  = int(strlen[0:1]) * 16 + int(strlen[1:2])
> ...     return "%s%s" % (chr(firstval), chr(lastval))
> ...>>> bcdlen(4546)
>
> 'FE'


Let me add that instead of an an-close-as-possible translation
from the  original Perl code, one can rewrite this as:

>>> def bcdlen(length):
...     strlen = "%04s" % length
...     return chr(int(strlen[2:4], 16)) + chr(int(strlen[0:2], 16))


which is more "Pythonic" to me.

--
Hope this helps,
Steven




More information about the Python-list mailing list