Prev: Running a program from another program.
Next: How to print SRE_Pattern (regexp object) text for debugging purposes?
From: Grant Edwards on 17 Jun 2010 16:29 On 2010-06-17, Stephen Hansen <me+list/python(a)ixokai.io> wrote: >>>> BIT_1 = 1 << 0 >>>> BIT_2 = 1 << 1 .... > 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". Just to clarify, "byte ^ BIT_X" inverts (toggles) bit X. If you want to make sure bit X is a 0 (which is what people usually mean by "unset"), you do "byte & ~BIT_X" -- Grant Edwards grant.b.edwards Yow! I know things about at TROY DONAHUE that can't gmail.com even be PRINTED!!
From: Stephen Hansen on 17 Jun 2010 17:39 On 6/17/10 1:29 PM, Grant Edwards wrote: > On 2010-06-17, Stephen Hansen <me+list/python(a)ixokai.io> wrote: > >>>>> BIT_1 = 1 << 0 >>>>> BIT_2 = 1 << 1 > > ... > >> 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". > > Just to clarify, "byte ^ BIT_X" inverts (toggles) bit X. > > If you want to make sure bit X is a 0 (which is what people usually > mean by "unset"), you do "byte & ~BIT_X" Doh, you're correct. I got so used to the pattern of only ever flipping the bit off after for some reason I knew it was on, like: if blah & CONSTANT_A: do-stuff blah = blah ^ CONSTANT_A That I forgot ^ was invert >_> Ahem! Thanks for the correction. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/
From: Anssi Saari on 19 Jun 2010 05:11
Back9 <backgoodoo(a)gmail.com> writes: > Hi, > > I have one byte data and want to know each bit info, > I mean how I can know each bit is set or not? Other than the tedious anding, oring and shifting, you can convert your byte to a string (with function bin) and use normal string handling functions to check if individual bits are 0 or 1. String format is also handy if you happen to need to do things like reversing the bit order or slicing and joining together various bits from different bytes. I seem to invariably need to do some bit order reversing when I mess around with serial data, which is one reason why I like Python. |