I've recently had an interesting mail exchange with one of the web thought reader about the ASP AND operator. I have used the AND operator in a previous post about alternating colours rows in a table and now I realise I haven't really explained how the AND operator works, and why it is useful in that situation and others.
If you try to output results, like our friend did, using a snippet like:
You get strange results. The series is:
Response.Write("("& i &"," &(i and 2) &"),")
That obviously raise a question: why we get that result?
And further more: how, in the end, is the AND operator working?
Other resultsIf we change some variables in the above code, and for example we set i=0, the result is a more coherent series, but we basically don't get a really true/false result.
That won't help us much in getting an alternating result as we needed for the alternating colours for rows. Eventually we might start wondering if the AND operator, the way we are using it, is really giving a true/false result... and it is not, as you can see.
So what is really doing? What is the actual AND operator output?
The AND operatorIt is a logical operator that compares Boolean values and returns Boolean results. When we use the AND operator the way we used it, we are doing a bitwise comparison:
"Bitwise operations evaluate two integral values in binary (base 2) form. They compare the bits at corresponding positions and then assign values based on the comparison." (quote from MSDN)
x = 3 and 5
That is why it works perfectly for our alternating colour rows: it gives us an alternating value of 0 and 1, like a true/false result.
"3 in binary form = 011
5 in binary form = 101
The And operator compares the binary representations, one binary position (bit) at a time. If both bits at a given position are 1, then a 1 is placed in that position in the result. If either bit is 0, then a 0 is placed in that position in the result. In the preceding example this works out as follows:
011 (3 in binary form)
101 (5 in binary form)
001 (The result, in binary form)
The result is treated as decimal. The value 001 is the binary representation of 1, so x = 1." (same source as above)
I hope that the above sheds some light about the use of the AND operator. A big thank you goes to Angel for pointing it out.