Solved How Logical Operator Used To Compare Integers!?

ADIGA88

Member
Local time
Today, 05:39
Joined
Apr 5, 2020
Messages
94
Hi guys,

I came across strange use of the AND Operator and I couldn't explain it if someone could shed some light on it. I found this example in the Access VBA MS Docs.

In the example, they use the AND to compare integers and it's not what you think (-1, 0)

Code:
Private Sub KeyHandler_KeyDown(KeyCode As Integer, _ 
     Shift As Integer) 
    Dim intShiftDown As Integer, intAltDown As Integer 
    Dim intCtrlDown As Integer 
 
    ' Use bit masks to determine which key was pressed. 
    intShiftDown = (Shift And acShiftMask) > 0 
    intAltDown = (Shift And acAltMask) > 0 
    intCtrlDown = (Shift And acCtrlMask) > 0 
    ' Display message telling user which key was pressed. 
    If intShiftDown Then MsgBox "You pressed the Shift key." 
    If intAltDown Then MsgBox "You pressed the Alt key." 
    If intCtrlDown Then MsgBox "You pressed the Ctrl key." 
End Sub
While (acShiftMask, acAltMask, acCtrlMask) are evaluate ( 1, 4, 2)


Thanks
 
Here's some more detail. if you consider two numbers

eg 43, which is byte 00101011

and 8 which is byte 00001000
or 4 which is byte 00000100

you can test for whether the byte representation value of 43 contains the particular bits representing 8 and 4 by anding the two values, which isn't obvious when considering them as base 10 numbers, but is when you consider the binary numbers. In binary, 43 is 32+8+2+1

so 43 00101011
and 8 00001000

Then 43 AND 8 returns 00001000 showing that for value 43 your "8" bit IS set

so 43 00101011
and 4 00000100

43 AND 4 returns 00000000 showing that for value 43 your "4" bit IS not set

Therefore you can use this technique to manage the 8 bits in a single byte as effectively 8 distinct "flags" and determine whether each of the 8 bits is set or not. This can be more efficient than using a whole byte for a simple on/off indicator, especially where each of the 8 bits are independent of each other.

The XOR operator is also particularly useful as you can use it to "toggle" a bit. If both bits are 1, it returns 0

so 43 XOR 8 gives 35, by turning off the "8" bit, and then 35 XOR 8 gives 43 again by turning it back on again.

43 = 00101011
8 = 00001000
using xor - 43 XOR 8 = 00100011 (= 35)
 

Users who are viewing this thread

Back
Top Bottom