Wednesday, 14 March 2012

ASP: the AND operator

   


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:
<%
   Dim i
   i=1
   while i<=15
      Response.Write("("& i &"," &(i and 2) &"),")
      i=i+1
   wend
%>
You get strange results. The series is:
(1,0),(2,2),(3,2),(4,0),(5,0),(6,2),(7,2),(8,0),(9,0),(10,2),(11,2),(12,0),(13,0),(14,2),(15,2),
That obviously raise a question: why we get that result?
And further more: how, in the end, is the AND operator working?

Other results
If 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 operator
It 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)
That means:
x = 3 and 5
"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)
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.

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.


0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.