[Tutor] working with c_byte?

Alan Gauld alan.gauld at btinternet.com
Sat Mar 24 09:14:24 CET 2012


On 24/03/12 03:51, Alex Hall wrote:

> Of course, 9 means the battery is high and charging, but how do I
> interpret an arbitrary integer as the sum of its flags? Is there a
> binary trick I can use?

Dave has given the immediate answer which is a subset of a general 
technique known as bitwise masking.

I discuss this with some other examples in the Operating System topic of 
my tutorial. You might find the write up interesting.

Another useful bitwise operator is xor which can be used to tell is any 
flags have changed value since the last time you looked:

oldflags = readFlags()

while True:   # look for a change
    newflags = readFlags()
    if newflags ^ oldflags:
        break # there's been a change

# process newflags.

And finally, the bitwise OR can be used to set a particular flag

HiBattery = 8

flags = flags | HiBattery  # sets HiBattery, preserving the rest.


HTH,

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list