Page History: Bit Manipulation Functions
Compare Page Revisions
Page Revision: 2020/09/20 13:04
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)
... 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:
In this code pack, note that the Inv() function replicates the native function of the same name present in MMBasic on the CMM2. This would make the FlagRes() CMM2 version shown at the bottom compatible with MicroMite MMBasic however it runs about 30% slower.
'preamble
Dim Integer Flag
'Set a Flag
Sub FlagSet(bit As Integer)
FLAG=FLAG Or 1<<bit
End Sub
'Clear a flag
Sub FlagRes(bit As Integer)
Local Integer x
x=1<<bit
FLAG=(FLAG Or x) Xor x
End Sub
'Equate a flag to a value
Sub FlagEq(bit As Integer,v As Integer)
If v Then
FlagSet(bit)
Else
FlagRes(bit)
Endif
End Sub
'Test a flag
Function FlagTest(bit As Integer) As Integer
FlagTest=Abs(Sgn(FLAG And 1<<bit))
End Function
'Bitwise Invert
'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.
'for CMM2
Sub FlagRes(bit As Integer)
FLAG=FLAG And Inv(1<<bit)
End Sub