How to convert a string to hex?

Suchandra Thapa ssthapa at midway.uchicago.edu
Fri Jun 23 10:08:40 EDT 2000


Sam Wun <swun at esec.com.au> wrote:
>Suppose here is:
>
>b = "6b584"
>
>I would like to b to hex. Does anyone know how to do that in python?
>

    Try this:
	
    def atoh(s, hexdigits = string.hexdigits):
	value = 0
	for char in s:
	    index = string.find(string.hexdigits, char)
	    if index >= 16:
		index = index - 6
	    value = value*16 + index
	return value
    
    This may not work in general but it works for the case you gave and
some other test case I tried out.  It should work for any string including
those where the hex digits are in caps or in mixed case just make sure
you strip thr leading 0x if its present and that the string passed in is
really a hex number.

-- 
------------------------------------------------------------------

Suchandra S. Thapa 
s-thapa at uchicago.edu

------------------------------------------------------------------



More information about the Python-list mailing list