Visual Basic

  1. Home
  2. Computing & Technology
  3. Visual Basic

Understanding How VB Logical Operators Work Bitwise

When is AND not AND? When you put the Byte on it!

By Dan Mabbutt, About.com

I'll bet you have a pretty good understanding of the logical operators And, Or, and Not already! If A is True and B is False, then A And B is False. And so forth. We're not going to go over the rest. You've probably seen it!

The two very rarely used VB 6 operators Imp and Eqv have disappeared in VB.NET, but two new operators, AndAlso and OrElse have been added. The VB.NET documentation suggests that you simply use the standard operators to accomplish the effect of Imp and Eqv. Here's Imp in code as an example.

'True unless A True and B False
Result = A Imp B
'Gives the same result
Result = (Not A) Or B

The two new VB.NET operators AndAlso and OrElse are used to short-circuit a logical evaluation by evaluating the second expression only if it's necessary. This is a way of thinking about expression evaluation that is familiar to C programmers but new to VB programmers.

But that isn't what this Quick Tip is all about. We're going to discuss what happens when something like this is evaluated (and why).

Dim A As Boolean
Dim B As Integer
A = True
B = 11
MsgBox(A Xor B)

So ... what does the MsgBox display?

Give up? Answer: -12

And this is the answer in both VB 6 and VB.NET.

The point of this is that logical operators work either on Boolean expressions (True or False, or something that evaluates to True or False) or integers that are evaluated "bitwise". When you have a mixed expression, like the one above, then the Boolean expression is evaluated as though it was a signed integer. This can be a useful technique (for example, to create your own "truth table" using the individual bits in a number) but it's even more useful to know if you happen to do it accidentally and you can't understand why your program is doing what it's doing.

When a logical operator evaluates two expressions "bitwise", they're converted into equal length integers and each bit is evaluated. So for the example above, True is the 16 bit number:

1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

The value 11 is:

0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1

And the XOR bitwise evaluation is:

1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 0

Which turns out to be -12 in VB's integer notation.

More Visual Basic Quick Tips

Explore Visual Basic

By Category

About.com Special Features

Visual Basic

  1. Home
  2. Computing & Technology
  3. Visual Basic
  4. Quick Tips
  5. Evaluating Logical Operators Bitwise in Visual Basic - the VB Xor Logical Operator

©2009 About.com, a part of The New York Times Company.

All rights reserved.