Bit Manipulation Functions
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 FLAG
Syntax:
FlagSet bit FlagRes bit FlagEq bit,value =FlagTest(bit)
Example:
FlagSet 17 FlagRes SDCARD_INSERTED IF FlagTest(PRINTER_READY)=0 THEN PRINT "Printer is not ready. Switch ONLINE and press Enter" FlagEq LeapFlag,IsLeapYear(2017)
Code: In this code pack, note that the Inv() function replicates the native function of the same name present in MMBasic on the CMM2. With this function, the FlagRes() CMM2 version shown at the bottom is compatible with MicroMite MMBasic but runs about 30% slower than the version immediately below.
'preamble Dim Integer Flag 'Set a Flag Sub FlagSet(b As Integer) Flag=Flag or &o1<<b End Sub 'Clear a flag Sub FlagRes(b As Integer) Flag=Flag Or &o1<<b Xor &o1<<b End Sub 'Equate a flag to a value Sub FlagEq(b As Integer,v As Integer) If v Then FlagSet(b) Else FlagRes(b) Endif End Sub 'Test a flag Function FlagTest(b As Integer) FlagTest=Abs(Sgn(Flags And (&o1<<b))) End Function 'Bitwise Invert, logical NOT 'For MMBasics without native Inv() Function Function Inv(a As Integer) Inv=a Xor &hFFFFFFFFFFFFFFFF End Function
Version of FlagRes() for CMM2 ...
Leverages the native Inv() function of MMBasic on CMM2 - simpler and a bit faster. Many thanks to TwoFingers and Turbo46 of TBS for optimizations and additional routines.
<code> 'for CMM2 Sub FlagRes(b As Integer) FLAG=FLAG And Inv(1<<b) End Sub
</code>