b2a_hex (data) or hexlify (data) funtionality in V1.5.2

Niels Diepeveen niels at endea.demon.nl
Tue Sep 19 16:38:00 EDT 2000


Jens Arnfelt schreef:
> ----------- snip ---------
> b2a_hex (data)
> hexlify (data)
>     Return the hexadecimal representation of the binary data. Every byte
> of data is
>     converted into the corresponding 2-digit hex representation. The
>     resulting string is therefore twice as long as the length of data.
> ------------ snip --------
> 
> Is there any way I can make, export, simulate, make or .. this function
> in Python 1.5.2.
> Unfortunately I'm not in a position to upgrade Python to V2.0 and I need
> the above functionality to be
> as fast as possible since this is where 90% of my CPU time is spent in
> my application.

Using the right algorithm makes a big difference. The fastest I could
come up with is this:

#-----------------------------------
import string

_hexbyte = {}  # setup lookup table
for _i in xrange(256):
    _hexbyte[chr(_i)] = '%02x' % _i

def bin2hex(s):
    t = range(len(s))  # preallocate intermediate list
    hexbyte = _hexbyte # get lookup table into local namespace
    for i in t:
        t[i] = hexbyte[s[i]]
    return string.join(t, '')
#-----------------------------------

On my system this is about 7 times faster than the map/lambda thing
(converting 1000 strings of 1000 bytes). Just don't put very large
strings into it, because of the memory needed for the intermediate list.

-- 
Niels Diepeveen
Endea automatisering



More information about the Python-list mailing list