On 6/17/10 12:51 PM, Back9 wrote:
> I have one byte data and want to know each bit info,
> I mean how I can know each bit is set or not?

>>> BIT_1 = 1 << 0
>>> BIT_2 = 1 << 1
>>> BIT_3 = 1 << 2
>>> BIT_4 = 1 << 3
>>> BIT_5 = 1 << 4
>>> BIT_6 = 1 << 5
>>> BIT_7 = 1 << 6
>>> BIT_8 = 1 << 7
>>> byte = 67
>>> if byte & BIT_1:
...     print "Bit 1 is set!"
... else:
...     print "Bit 1 is not set!"
Bit 1 is set!
>>> if not byte & BIT_6:
...     byte = byte | BIT_6
...     print "Bit 6 wasn't set, BUT NOW IS."
Bit 6 wasn't set, BUT NOW IS.
>>> byte
99

(I added 'how to set a specific bit' just cuz)

Basically, those BIT_X lines are creating numbers which have *only* the
specified bit set. Then you do "byte & BIT_X", and that will return 0 if
the byte doesn't have the specified bit in it. You can then set the bit
with "byte | BIT_X", and unset the bit with "byte ^ BIT_X".

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/

Attachment: signature.asc
Description: OpenPGP digital signature

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to