Page History: Bit Manipulation Functions
Compare Page Revisions
Page Revision: 2020/09/18 20:51
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:
Sub FlagSet(bit As Integer)
FLAG=FLAG OR (1<<bit)
End Sub
Sub FlagRes(bit As Integer)
Local Integer x
x=1<<bit
FLAG=(FLAG Or x) Xor x
End Sub
Sub FlagEq(bit As Integer,v As Integer)
If v Then
FlagSet(bit)
Else
FlagRes(bit)
Endif
End Sub
Function FlagTest(bit As Integer) As Integer
FlagTest=Abs(Sgn(FLAG And (1<<bit)))
End Function