Converting strings to hex
Kris J. Zaragoza
kzaragoza at mediaone.net
Thu May 18 23:20:58 EDT 2000
On Thu, 18 May 2000 19:24:41 -0700, emile at fenx.com <emile at fenx.com> wrote:
>As long as we're contributing methods, I use this:
>
>def hta(s, padlen=1):
> """ hta(string) returns a hex repr of string"""
> if not s:
> return ""
> elif type(s)<>type("string"):
> raise "argument should be of type string"
> elif len(s)<padlen:
> while len(s)<padlen:
> s = '\000' + s
> h = ""
> for c in s:
> h = h + '%2x' % ord(c)
-------------------^
This formatting string is going to return a space-padded number. If
that's what you're looking for, great. I'm accustomed to getting
zero-padded numbers, where "\001" would be represented as "01" instead
of " 1". For zero-padding, you need to use the format string "%02x"
or, "%02X" if you want upper-case letters (A-F).
> return h
>
>Emile van Sebille
>emile at fenx.com
>
>
>> It must be something in the air. I also needed this yesterday and a
>> DejaNews search yielded this function from Michael Wallace.
>>
>> def hexify(binaryString):
>> result = ""
>> for i in binaryString:
>> result = result + string.zfill(hex(ord(i))[2:],2)
>> return result
>>
>> Jay
>>
>>
>> --
>> http://www.python.org/mailman/listinfo/python-list
>>
>
--
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