[Wolves] Bitwise AND

Aquarius aquarius-lists at kryogenix.org
Tue Jan 6 11:53:28 GMT 2004


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_MATT_REVELL  = 1
FLAG_AQ           = 2
FLAG_JONO         = 4
FLAG_SPARKES      = 8
FLAG_PETER_OLIVER = 16
FLAG_LEE_JORDAN   = 32
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.

Aq.

-- 
UTF-8 has a certain purity in that it equally annoys every nation, and
is nobody's default encoding.
	   -- Andy Robinson, 10 Apr 2000



More information about the Wolves mailing list