User Tools

Site Tools


mmbasic:bit_manipulation_functions

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(bit As Integer)
		FLAG=FLAG Or 1<<bit
	End Sub

	'Clear a flag
	Sub FlagRes(bit As Integer)
		FLAG=(FLAG Or 1<<bit) Xor 1<<bit
	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, 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(bit As Integer)
	FLAG=FLAG And Inv(1<<bit)
End Sub

</code>

mmbasic/bit_manipulation_functions.txt · Last modified: 2024/01/19 09:30 by 127.0.0.1