Converting strings to hex
Kris J. Zaragoza
kzaragoza at mediaone.net
Thu May 18 20:28:46 EDT 2000
On Fri, 19 May 2000 01:11:05 +0100, Dale Strickland-Clark
<dale at out-think.NOSPAMco.uk> wrote:
>The output from MD5.digest() is a 16 byte binary string.
>
>I want to convert it to hex for printing.
>
>The hex() function only handles integers (pah!) so I've come up with this:
>
>def wibble(r):
> return hex(ord(r))[2:4]
>
>a=md5.new(data).digest()
>string.join(map(wibble, list(a)), "")
>
>Which is ugly, at best.
>
>Is there a better way?
>
>hhmm...
>
>I've just discovered unpack and come up with this:
>
>"%4X %4X %4X %4X" % struct.unpack(">4i", a)
>
>which is certainly shorter!
>
>Is this the best I can expect?
>
>Thanks
>
>--
>Dale Strickland-Clark
>Out-Think Ltd, UK
>
>
>
That's funny, I was _just_ playing with this very functionality!
Here's what I came up with:
def md5ToHex(md5string):
import string
ret = []
for c in md5string:
ret.append("%02X" % ord(c))
return string.join(ret,"")
Running this:
>>> import md5
>>> m = md5.new("Foo!").digest()
>>> m
"\333h(\246'\355i_\373\201\2445<\342\222n"
>>> md5ToHex(m)
'DB6828A627ED695FFB81A4353CE2926E'
>>>
Is this what you're looking for?
-Kris
--
Kris J. Zaragoza | "Unfortunately, most people can't out-think a
kzaragoza at mediaone.net | grapefruit." --Jon Bodner
More information about the Python-list
mailing list