newbie question: any better way to write this code?
Jean-Paul Calderone
exarkun at divmod.com
Wed Dec 27 10:44:06 EST 2006
On 27 Dec 2006 07:18:22 -0800, neoedmund <neoedmund at gmail.com> wrote:
>i want to let a byte array to be xor with some value.
>but code show below i wrote seems not so .. good..., any better way to
>write such function? thanks.
>[code]
>def xor(buf):
> bout=[]
> for i in range(len(buf)):
> x = ord(buf[i])
> x ^= 123
> bout.append(chr(x))
> return "".join(buf)
>buf = "xxxxxxxx".encode("utf8")
>buf = xor(buf)
>
You can use numarray to do the same thing much more easily:
>>> import numarray
>>> buf = numarray.array('xxxxxxxx')
>>> buf.tostring()
'xxxxxxxx'
>>> (buf ^ 123).tostring()
'\x03\x03\x03\x03\x03\x03\x03\x03'
>>>
In any case, you can at least drop the '.encode("utf8")'. "xxxxxxx"
is already a byte string, there is no need to encode it.
Jean-Paul
More information about the Python-list
mailing list