Reverse order of bit in repeating seqence of byte string

John Machin sjmachin at lexicon.net
Sat Jan 3 01:33:28 CET 2009


On Jan 3, 5:34 am, imageguy <imageguy1... at gmail.com> 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.

For some very strange definition of "works". You say you have 'bgr'
and want to convert it to 'rbg'. The following code converts 'bgr' to
'rgb', which is somewhat more plausible, but not what you said you
wanted.

>
> 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)
>




More information about the Python-list mailing list