Do It Bitwisely: Manage Several Controls With Just A Single Number

Sir Isaac

Member
Bits are not for rocket scientists only. They come in handy in pretty common programming tasks, for instance, when dealing with a complex system of controls. Here's a snippet demonstrating how to get and set checked states for 4 check-boxes with a single number (0 to 15, naturally) in Basic4PPC. Perhaps, this is too simple for the present company, however, I believe the more examples the better.

B4X:
Sub Globals 'First add a Bitwise object named bit.
Box=0 'Variable for a decimal value
End Sub
Sub App_Start 'ADDING CONTROLS TO THE FORM
AddNumUpDown("frmMain","numBitCount",80,70,40) 'Adds a decimal counter with Value_Changed event
AddEvent("numBitCount",ValueChanged,"numBitCount_ValueChanged")
numBitCount.Maximum = 15
AddLabel ("frmMain","lblDisplay",130,72,40,16,"0000") ' Adds a binary display
lblDisplay.Color = Rgb(220,220,220)
For i = 0 To 3 'Adds 4 checkboxes with Click events
   AddCheckBox ("frmMain","chkTrigger"&i,30+(i*50),160,40,30,""&i)
   AddEvent("chkTrigger"&i,Click,"Trigger_Click")
   Button("chkTrigger"&i).Color = Rgb(220,220,220)
Next i
bit.New1 'Constructs a bitwise object
   frmMain.Show
End Sub
Sub numBitCount_ValueChanged ' Sets checked values of the checkboxes
Box = numBitCount.Value
   For i = 0 To 3
      Button("chkTrigger"&i).Checked = bit.GetBit(Box,i)
   Next
lblDisplay.Text=Format(bit.DecToBin(Box),"D4") 'Binary representation of a decimal value
End Sub
Sub Trigger_Click 'Sets a corresponding bit to 1/0 if a checkbox is checked/unchecked
If Sender.Checked = True Then Box = bit.SetBit(Box,Sender.Text) Else Box = bit.ClearBit(Box,Sender.Text) 
numBitCount.Value = Box
End Sub
 
Last edited:
Top