Use Logical AND to Determine Which Bits Are Set in an Integer (32730)



The information in this article applies to:

  • Microsoft Visual Basic for MS-DOS
  • Microsoft QuickBASIC 4.0
  • Microsoft QuickBASIC 4.0b
  • Microsoft QuickBASIC 4.5
  • Microsoft BASIC Compiler for MS-DOS and OS/2
  • Microsoft Basic Professional Development System (PDS) for MS-DOS and MS OS/2 7.0
  • Microsoft Basic Professional Development System (PDS) for MS-DOS and MS OS/2 7.1
  • Microsoft QuickBASIC Compiler for the Apple Macintosh 1.0
  • Microsoft GW-Basic Interpreter 3.20
  • Microsoft GW-Basic Interpreter 3.20 and later

This article was previously published under Q32730

SUMMARY

The logical AND operator can be used in Basic to determine which bits are set. For example, the program below determines whether a bit has been set in the High or Low byte of a 2-byte integer variable.

MORE INFORMATION

The CALL INTERRUPT or INT86OLD functions in Visual Basic for MS-DOS return information by setting certain bits in the AH or AL register. The program listed below determines whether a bit has been set in the High or Low byte of a 2-byte integer variable:
' To try this example in VBDOS.EXE:
' 1. From the File menu, choose New Project.
' 2. Copy the code example to the Code window.
' 3. Press F5 to run the program.

INPUT x%  'Give it an integer value.
PRINT "Bits set in the High byte of x%."
IF x% < 0 THEN PRINT "Bit 7 set!"
mask% = &H4000
FOR i% = 6 TO 0 STEP -1
   IF x% AND mask% THEN PRINT "Bit"; i%; " set!"
   mask% = mask% \ 2
NEXT
PRINT "Bits set in the Low byte of x%."
' For just the Low byte, mask% starts out as 128.
FOR i% = 7 TO 0 STEP -1
   IF x% AND mask% THEN PRINT "Bit"; i%; " set!"
   mask% = mask% \ 2
NEXT
				

Modification Type:MinorLast Reviewed:8/16/2005
Keywords:KB32730