Reverse order of bit in repeating seqence of byte string

imageguy imageguy1206 at
Sat Jan 3 21:10:15 CET 2009

On Jan 2, 7:33 pm, John Machin <sjmac... at> wrote:

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

Well that's embarrassing ... you are correct.  I need to convert from
'bgr' to 'rgb'

Thanks to all others for suggestions

FWIW, I realized the the C.types string buffer is/was mutable so
settled on this;

for start in xrange(0, ctypes.sizeof(buffer), 3):
    if buffer[start] != buffer[start+2]:
         #only need to swap the bits if they are different.  ie if
both are white or black, no change is required.
         blue, red = buffer[start], buffer[start+2]
         buffer[start], buffer[start+2] = red, blue

This was about 30-40% faster that converting to list, processing and
then converting back again.

Will try the array module too
... but I think I need to find a new graphic package rather that makes
working with the bits easier.


More information about the Python-list mailing list