how to get bit info

Stephen Hansen me+list/python at ixokai.io
Thu Jun 17 16:14:05 EDT 2010


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/

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 487 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20100617/d084f38e/attachment-0001.sig>


More information about the Python-list mailing list