Help needed with translating perl to python

Duncan Booth duncan.booth at invalid.invalid
Thu Jun 28 04:31:04 EDT 2007


attn.steven.kuo at gmail.com wrote:

> 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.

Throwing an exception for values of length less than 100 doesn't seem 
terribly good. Did you mean "%04d"?

Personally I think I'd split the number up before round-tripping through 
the string. Maybe:

def bcdbyte(b):
    return chr(int(str(b), 16))

def bcdlen(length):
    return bcdbyte(length%100) + bcdbyte(length//100)




More information about the Python-list mailing list