Reverse order of bit in repeating seqence of byte string
Gary Herron
gherron at islandtraining.com
Fri Jan 2 20:05:35 EST 2009
imageguy wrote:
> I am looking for the most efficient method of replacing a repeating
> sequence in a byte string returned from a imaging .dll, connected via
>
> I receive the byte string with the following sequence 'bgrbgrbgrbgr'
> and I would like to convert this to 'rbgrbgrbgrbg'
> FWIW, the string is created using ctypes.create_string_buffer function
>
> The following code works but feels a bit clunk and is rather slow too.
>
> blist = list(buffer)
> for start in xrange(0,len(blist), 3):
> try:
> blue = blist[start]
> red = blist[start+2]
> blist[start] = red
> blist[start+2] = blue
> except IndexError:
> pass
>
> new_buffer = ''.join(blist)
>
> new_buffer is then passed to a wx program to create and image.
>
> Any thoughts comments would be appreciated.
>
> geoff.
>
> PS: I started this post earlier, but I think I hit the send button
> too soon. My apologies to the group for sloppy typing.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
I've not seen anyone mention numpy yet, but
numpy has a nice (efficient) way to do this:
>>> import numpy
>>> s = 'bgrBGRcbaCBA'
>>> a=numpy.array(s, 'c') # Initialize an array
>>> a.shape = (4,3) # Reinterpret as a ?? by 3 array
>>> b=a[...,::-1] # reverse the second dimension
>>> print b.tostring() # Convert back to a string.
rgbRGBabcABC
Gary Herron
More information about the Python-list
mailing list