Welcome Guest, you are in: Login

Fruit Of The Shed

Navigation (MMBasic)






Search the wiki

»


Page History: Bit Manipulation Functions

Compare Page Revisions



« Older Revision - Back to Page History - Newer Revision »


Page Revision: 2016/12/29 08:59


The following three functions provide SETting, RESetting and TESTing of individual bits of an integer expression (ideally a variable). This makes using single bits as flags easy and far more memory-kind than using integer variables as flags (which wastes 8 bytes per flag).
With this method, up to 64 flags can be maintained in a single integer variable. If CONST is used to define the bits it makes for very readable code.

In the interests of speed, there is no error checking on the bit you manipulate. If you try anything outside the range 0 to 63, you'll get weird results at best.

I like FUNCTIONs (so you can assign the result of an operation anywhere - VB, old habits die hard - gives maximum flexibility). If you don't, the modified code using SUBs is further down. They work only with a single variable - which is probably fine in most case, 64 flags is probably enough for even the busiest apps.

Syntax:
BitSet(expression,bit)
BitRes(expression,bit)
... BitTest(expression,bit)= ...

Example:
FLAGS=BitSet(FLAGS,PRINTER_READY)
IF BitTest(FLAGX,OUTPUT_FORMAT)=0 THEN DumpTXT ELSE DumpCSV

Code:
 
  FUNCTION  BitSet(value AS INTEGER, bit AS INTEGER) AS INTEGER
    BitSet=value OR (2^bit)
  END FUNCTION 


  FUNCTION BitRes(value AS INTEGER, bit AS INTEGER) AS INTEGER
    BitRes=(value OR (2^bit)) XOR (2^bit)
  END FUNCTION 


  FUNCTION BitTest(value AS INTEGER, bit AS INTEGER) AS INTEGER
    BitTest=ABS(SGN(value AND (2^bit)))
  END FUNCTION


Adapted SET/RES to SUBs assumes a global integer called FLAGS - will be slightly faster and names changed to make it obvious

Syntax:
FlagSet(bit)
FlagRes(bit)
... FlagTest(bit)= ...

Example:
FlagSet OUTPUT_FORMAT
FlagRes SDCARD_INSERTED
IF FlagTest(PRINTER_READY)=0 THEN PRINT "Printer is not ready. Switch ONLINE and press Enter"

Code:

  SUB FlagSet(bit AS INTEGER)
    FLAGS=FLAGS OR (2^bit)
  END SUB  


  SUB FlagRes(bit AS INTEGER)
    FLAGS=(FLAGS OR (2^bit)) XOR (2^bit)
  END SUB 


  FUNCTION FlagTest(bit AS INTEGER) AS INTEGER
    FlagTest=ABS(SGN(FLAGS AND (2^bit)))
  END FUNCTION