bit manipulation frustration

Mike Fletcher mfletch at tpresence.com
Sun Jul 23 01:20:14 EDT 2000


Convoluted, yes, but this might give you some ideas for manipulations (or it
might give you convulsions ;0) )...

import struct
def toRGB( line ):
	line = struct.unpack( 'H'*len(line), line)
	result = []
	R = 64512
	G = 2016
	B = 63
	for integer in line:
		result.append( (
			R&integer >> 10,
			G&integer >> 5,
			B&integer,
		) )
	return result

def toString( line ):
	result = []
	for r,g,b in line:
		result.append( 
			r << 10 + g << 5 + b
		)
	return apply( struct.pack, ( 'H'*len(result),)+tuple(result) )

Oh, in case you're wondering, this will be _ridiculously_ slow, Python's not
good at bit-fiddling :) .  That's one reason PIL's C extensions exist :) .
You'll probably find something that can read 16-bit integers into RGB values
somewhere in the codebase.

HTH,
Mike

-----Original Message-----
From: Courageous [mailto:jkraska1 at san.rr.com]
Sent: Sunday, July 23, 2000 12:56 AM
To: python-list at python.org
Subject: Re: bit manipulation frustration



> > vice versa. Eeek. Help? Will someone please remind me and
> > hit me with a rubber mallet??? :)

> ... is one way. There are probably others. Consider youself whalloped.

Yeah, amongst all the various documentation, I finally found my
way to FAQTS. It was:

>>> l=list("fred")
>>> l
['f', 'r', 'e', 'd']
>>> string.join(l,"")
'fred'
>>> 

> > Second, this whole paradigm seems so skrewball.
> ...
> > get it?)

Um, well suppose I do something like...

            myfile.seek ( 2000, 0 )
            str = myfile.read (20)

This will result in a sequence of 20 bytes ('char'),
But these are 16 bit RGB values (1 pad, 5/5/5 R/G/B).
In C, I would quite possibly load these into ints,
as 16 bit values straight up, and manipulate them that
way. Now while I understand that I can unpack into
16 bit integers, manipulate, and then pack back to
char all via the struct module, this is seeming like
a great deal of transmogrification.

Say for example I want to increase or decrease R,
G, or B values. Or, say, I want to convert to 32
bit color bitmaps?



C/
-- 
http://www.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list