Page 1 of 1

Logical AND difficulties...

Posted: Mon Jun 30, 2014 9:26 am
by jejump
Okay, here's an interesting (...and frustrating) problem...

I'm programming in QBX 7 and in my main module of my program, I have stated:

COMMON SHARED MachineStatus AS INTEGER

In one of my SUBs I have this piece of code:

IF MachineStatus AND 7 THEN 'Bits 0, 1, and 2 active
LOCATE 1,1 : PRINT MachineStatus : STOP 'For debug purposes
.
.
.
.
END IF

When I observe the screen output after the STOP, it's displaying 4, which clearly doesn't AND with 7. I use this same technique elsewhere in my program without this problem occurring.

Any ideas?

Thanks in advance,

John

Re: Logical AND difficulties...

Posted: Mon Jun 30, 2014 10:14 am
by burger2227
Bits 0, 1 and 2 are 1, 2 and 4. Thus any combination of the bits will AND with 7

Code: Select all

DIM SHARED MachineStatus AS INTEGER

MachineStatus = 7 'change value to lower values to see bits set

FOR i = 0 TO 2  'get bits on with exponents of 2
  IF 2 ^ i AND MachineStatus THEN bits = bits + 1: PRINT "1"; ELSE PRINT "0";
NEXT

IF bits = 3 THEN PRINT " OK"
PRINT bits; " bits on"
PRINT MachineStatus AND 7 
IF (MachineStatus AND 7) = 7 THEN PRINT "All 3 bits are on"
bit on = 1 with values of 1, 2 or 4. bits on = 2 with values of 3, 5 and 6. Only 7 will have all 3 bits on.

COMMON is only used when passing values to multiple modules

Re: Logical AND difficulties...

Posted: Mon Jun 30, 2014 10:50 am
by jejump
You've come to my rescue again burger. I can't believe this has never before been an issue for me. This seems to work fine now like this:

IF (MachineStatus AND 7) = 7 THEN 'Parenthesis are required
.
.
.
END IF

Thanks again for educating me :)

John

Re: Logical AND difficulties...

Posted: Mon Jun 30, 2014 11:03 am
by jejump
I guess the reason it's never been a problem before is because I usually always check for single bits and not for multiple bits at once with AND logic in QB. In all lower level languages I've ever programmed in, ALL three bits would have to be equal for like a CMP (compare) instruction. I guess I had it in my head that QB was making an automatic $$$ after stripping bit 3 thru bit 15, but I guess its view on it is that the result didn't equal 0.

So, in an effort to saver face from my opening statement....

Yes, 4 DOES AND with 7, but only by 33-1/3% and I was looking for 100% after gating. :oops:

Jj