[Wolves] Bitwise AND

sparkes sparkes at phreaker.net
Wed Jan 7 20:56:12 GMT 2004

On Tue, 2004-01-06 at 11:27, Aquarius wrote:
> Matthew Revell spoo'd forth:
> > if ($n & 1 = 1) return "odd";
> > 
> > then the reason it can let you know if a number is odd or even is because
> > it can only ever match all the numbers with 1 if the number is odd.
> Sort of. Odd numbers in binary form always have a 1 at the end, because
> they will always have a (1*1) in their binary makeup. (You add together
> 1s, 2s, 4s, 8s, 16s, etc to get the number, and all the things you add
> are even except the 1, so any odd number must have the 1 in it).
> Therefore, any number AND 1 will be 1 if it has a binary 1 in it (i.e.,
> is odd) and 0 if it doesn't (i.e., is even).
> > So, that's cool, but what else would you want to use it for?
> It's useful if you want to compress a set of flags into one number.
> Imagine that we wanted to show who was at a LUG meeting. YOu might do
> this by defining a load of flags:
> FLAG_AQ           = 2
> FLAG_JONO         = 4
> FLAG_SPARKES      = 8
> FLAG_HELEN        = 64
> and then add up the flags to get a number for each LUG meeting. Say
> that you, I, and sparkes were at a meeting: the number for that meeting
> would be 8 + 2 + 1 = 11. Now, you can then find out whether a given
> person was at the meeting by ANDing the meeting number with the flag
> for that person. So 11 AND FLAG_JONO = 0, so Jono wasn't there. 
> 11 AND FLAG_AQ = FLAG_AQ, so I was there. Useful little trick.
this is how most low level (ie stuff Aq wouldn't do in python) is done

If Aq agrees that python is not the best solution then the code will
most likly be stuffed with flags like this.  I think I mentioned at the
last meeting using unions and this is how they are used.  Sometimes you
refer to the bit in question and sometimes you want to look at the word
(byte or whatever size chunk in question).  Using logic like this as a
mask you can still see the individual bits.

> Aq.

More information about the Wolves mailing list