Welcome, guest | Sign In | My Account | Store | Cart

Qoute string converting each char to hex repr and back

Python, 14 lines
#convert string to hex
def toHex(s):
    lst = []
    for ch in s:
        hv = hex(ord(ch)).replace('0x', '')
        if len(hv) == 1:
            hv = '0'+hv
    return reduce(lambda x,y:x+y, lst)

#convert hex repr to string
def toStr(s):
    return s and chr(atoi(s[:2], base=16)) + toStr(s[2:]) or ''


sasa sasa 17 years, 8 months ago  # | flag

list comprehensions. Though your snippet is nice, you should really have a look at least comprehensions. With a few built-in methods you can reduce your 8 lines of code (which is pretty slow because of the "extra work" I guess) to one:

toHex = lambda x:"".join([hex(ord(c))[2:].zfill(2) for c in x])

The builtin string-method "join" joins every element of the list to the string by re-using the string. ";;".join(['a', 'b', 'c']) would result in 'a;;b;;c'. Note that you can enhance the speed of the above snippet by replacing the [] with () what will change it from a list comprehension to a generator. Same enhancements can be done with your second function.

Regards, Stargaming

tomer filiba 17 years, 8 months ago  # | flag

encode and decode. this functionality already exists with the encodings library (which is built-in):

>>> "hello".encode("hex")
>>> "68656c6c6f".decode("hex")
Adam Monsen 17 years ago  # | flag

base 16 int conversion. The hex() and int() builtins should do everything you need...

>>> int('0x10AFCC', 16)
>>> hex(1093580)
Adam Monsen 17 years ago  # | flag

Nevermind, I should've read the original post more closely. As the other commenter said, str.encode() and str.decode() do the same thing as your code.

a 14 years ago  # | flag

atoi() is deprecated. you should use int() instead

sic_uk 13 years, 10 months ago  # | flag

Even though modern Python implementations have .encode and .decode, old versions (pre v2) don't.

My current Python platform (Telit GC864) runs on v1.5.2, with absolutely no option to upgrade.

Thanks OP!

Alex Huszagh 8 years, 1 month ago  # | flag

On Python 3.x, this is depricated. The hex codec has been removed because it made absolutely no sense (thanks to Lennart Regebro on Stack Overflow). (You are not changed the codec of an 8-bit string, you are rather converting it, so using a "hex" codec is weird to say the least). Rather, the proper way to do this is:

>>> import binascii
>>> binascii.hexlify(b'Blaah')
Created by Mykola Kharechko on Fri, 18 Aug 2006 (PSF)
Python recipes (4591)
Mykola Kharechko's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks