newbie string conversion question
Scott David Daniels
scott.daniels at acm.org
Sat Apr 1 13:07:55 EST 2006
Rohit wrote:
> As part of a proprietary socket based protocol I have to convert a
> string of length 10,
>
> say, "1234567890"
>
> to send it as 5 characters such that their hex values are
>
> 0x21 0x43 0x65 0x87 0x09
>
> (Hex value of each character is got by transposing two digits at a
> time)
>
> How can I do this in python? I would like the result to be available
> as a string since I am concatenating it to another string before
> sending it out.
>
> Thanks,
> Rohit
>
For a horrendously obscure version, try:
def mangle(digits):
length = (len(digits) + 1) >> 1
v = int(digits, 16)
mask = int('0F' * length, 16)
smunch = (v ^ (v >> 4)) & mask
swapped = v ^ (smunch | (smunch << 4))
return ''.join(chr(255 & (swapped >> (8 * n)))
for n in reversed(range(length)))
--Scott David Daniels
scott.daniels at acm.org
More information about the Python-list
mailing list