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: 2018/09/18 10:33


The following four functions provide SETting, RESetting and TESTing of individual bits of an integer expression (ideally a variable). FlagEq sets a flag to the value specified (i.e. not mandating a set or reset). A non-zero value counts as 1. Ideal for state machine and event driven code.

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). This method allows up to 64 flags to be maintained using 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.

Assumes a global integer called FLAGS

Syntax:
FlagSet(bit)
FlagRes(bit)
... FlagTest(bit)= ...
FlagEq(bit, value)

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

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 
  
  
  SUB FlagEq(bit As Integer,v as integer)
    IF v=0 THEN
      FlagRes(bit)
    ELSE
      FlagSet(bit)
    ENDIF
  END SUB


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