swapping numeric items in a list
Fredrik Lundh
fredrik at pythonware.com
Wed Aug 23 15:13:49 EDT 2006
Jiang Nutao wrote:
> array.byteswap() won't work for me easily. I tried this before my 1st post.
> I defined
>
> aa = array('H', [0x12, 0x34, 0x56, 0x78])
>
> Then did byteswap aa.byteswap(). The result was
>
> array('H', [0x1200, 0x3400, 0x5600, 0x7800])
>
> You can see it byteswapped within each item.
you need to do things in the right order; first convert to bytes, then
build a 16-bit array, and then byteswap that array.
from array import array
# convert data array to 8-bit byte buffer
buf = array("B", [0x12, 0x34, 0x56, 0x78]).tostring()
# treat byte buffer as list of 16-bit integers
buf = array("H", buf)
buf.byteswap()
buf = buf.tostring() # convert back to bytes
[hex(ord(c)) for c in buf]
-> ['0x34', '0x12', '0x78', '0x56']
</F>
More information about the Python-list
mailing list