[Tutor] how to read one bit of a byte

Alan Gauld alan.gauld at btinternet.com
Wed Feb 21 21:57:17 CET 2007


"shawn bright" <nephish at gmail.com> wrote 

> but how do i read the individual bits of a byte
> how do i know what the msb of a is ?

See my reply to Johan in the thread Struct the solution...

Basically you can use a bitwise and with a mask 
containing only the bit you are interested in. Johan 
wanted the 8th bit so the mask was 10000000 = 0x80

Thus

bit8 = 0x80

if data & bit8: print 'bit 8 is 1'
else: print 'bit 8 is 0'

See my Using the OS topic sidebar for more info on bitmasks.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list