devxlogo

Packing Check-Box Values into a Single Integer

Packing Check-Box Values into a Single Integer

Use this code to find the binary representation of the currently checked check boxes:

 Function WhichCheck(ctrl As Object) As _	Integer' This function returns the binary value ' of an array of controls where the ' value is 2 raised to the index of each ' checked control' ie element 0 : 2 ^ 0 returns 1'elements 0 and 2 : 2^0 + 2^2 returns 5	Dim i	Dim iHolder	' in case ctrl is not a valid object	'default to failure return =0 on 	'fail	On Error GoTo WhichCheckErr	' find the binary representation of 	' an array of check box controls	For i = ctrl.LBound To ctrl.UBound		If ctrl(i) = 1 Then			' if it is checked add in its 			' binary value			iHolder = iHolder Or 2 ^ i		End If	NextWhichCheckErr:	WhichCheck = iHolderEnd Function

Call the function with code like this:

 iCurChecked = WhichCheck(Check1)

Check1 is an array of check boxes, and iCurChecked is an integer. Here’s the “dual” routine that sets the state of all the check boxes in a control array given an Integer that holds their binary representation:

 Sub SetChecked(ctrl As Object, _	iCurCheck%)' This sub sets the binary value of an ' array of controls where iCurChecked is ' 2 raised to the index of each checked ' control	Dim i	' in case ctrl is not a valid object	On Error GoTo SetCheckErr	' use the binary representation to 	' set individual check box controls	For i = ctrl.LBound To ctrl.UBound		If iCurCheck And (2 ^ i) Then			' if it is checked add in its 			' binary value			ctrl(i).Value = 1		Else			ctrl(i).Value = 0		End If	NextSetCheckErr:End Sub

Call the sub with code like this:

 Call SetChecked(Check1, iDesired)

Check1 is an array of checkboxes, and iDesired is a binary representation of the desired settings.

See also  How IoT Tech Will Transform Logistics
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist