Python version of binascii.b2a_hex (binary to hex conversion)?

Barry A. Warsaw barry at digicool.com
Fri Apr 27 16:42:58 EDT 2001


>>>>> "GG" == Graham Guttocks <graham_guttocks at yahoo.co.nz> writes:

    GG> I need to support Python < 2.0 with one of my apps that uses
    GG> binascii.b2a_hex and binascii.a2b_hex to convert between
    GG> binary data and it's hexadecimal representation.  Since these
    GG> functions aren't available in earlier Python versions, I need
    GG> to implement them myself.

    GG> For binary --> hex, I've found the following in the list
    GG> archives:

    |   def hexlify(b):
    |       return "%02x"*len(b) % tuple(map(ord, b))

    GG> I couldn't find the reverse (hexadecimal string --> binary
    GG> data).  Does anyone have such a function handy?

I remember a fairly in-depth thread a few years ago before I added
those functions to binascii, about the best pure Python approaches.
As expected, Tim Peters posted some of the fastest implementations.

Here's what I used in Mailman up until the current 2.1 alphas (which
require Python 2.x so just use the binascii functions).  Perhaps not
the fastest algorithms, but they work just fine.

-Barry

-------------------- snip snip --------------------
# Not the most efficient of implementations, but good enough for older
# versions of Python.
def hexlify(s):
    acc = []
    def munge(byte, append=acc.append, a=ord('a'), z=ord('0')):
	if byte > 9: append(byte+a-10)
	else: append(byte+z)
    for c in s:
	hi, lo = divmod(ord(c), 16)
	munge(hi)
	munge(lo)
    return string.join(map(chr, acc), '')

def unhexlify(s):
    acc = []
    append = acc.append
    # In Python 2.0, we can use the int() built-in
    int16 = string.atoi
    for i in range(0, len(s), 2):
	append(chr(int16(s[i:i+2], 16)))
    return string.join(acc, '')




More information about the Python-list mailing list