PDA

View Full Version : vBulletin and Binary values


keith1995
09-20-2007, 05:09 PM
Anyone familar with vBulletin and the binary values it assigns to multi-select checkboxes?

We are developing a vBulletin site with a member profile subcomponent and are using the multi-select checkboxes for two form fields. vBulletin stores the values of the selected checkboxes as a binary value, using the "to the xth power" and I don't quite know how to decode that so we can display which checkboxes are selected in the member profile.

vBulletin has its own member profile system but we'd like to create one outside of its template system which is why we need to try and decode these values.

For example, we have the following field (its value is in paratheses):

Geographical Areas:
Northeast (1)
Mid-Atlantic (2)
Southeast (4)
Midwest (8)
Southwest (16)
West Coast (32)
Canada (64)
China (128)
India (256)
Europe (512)
South America (1024)
Other (2048)

As I'm sure you are aware, the values are determined by taking the checkbox's number and times it to the 2nd power.

The problem is that vBulletin adds up the values of the selected checkboxes and stores that number. For example, 67 would mean that Northeast, Mid-Atlantic and Canada were selected.

Anyone know how to decode this value using PHP so I can display which checkboxes are selected?

Inigoesdr
09-20-2007, 07:12 PM
Your best bet is probably http://www.vbulletin.org/ or the vb.com forums, or the docs might have something on it.

CFMaBiSmAd
09-20-2007, 07:52 PM
You can use a bitwise and operator & and then check if the results are zero or not to tell if a bit is set. The following partial code is for demonstration purposes of how you might do this, and is not meant to be the best method and only checks the first two bits (tested) -
<?php
$Northeast = 1;
$Mid_Atlantic = 2;
$Southeast = 4;
$Midwest = 8;
$Southwest = 16;
$West_Coast = 32;
$Canada = 64;
$China = 128;
$India = 256;
$Europe = 512;
$South_America = 1024;
$Other = 2048;

$value = 3;

if(($value & $Northeast) <> 0)
{
echo "Northeast bit was set<br ?>";
}

if(($value & $Mid_Atlantic) <> 0)
{
echo "Mid_Atlantic bit was set<br ?>";
}
?>

CFMaBiSmAd
09-21-2007, 01:13 AM
Here is a more useful version of the code -
<?php
$bits = array();
$bits['Northeast'] = 1;
$bits['Mid_Atlantic'] = 2;
$bits['Southeast'] = 4;
$bits['Midwest'] = 8;
$bits['Southwest'] = 16;
$bits['West_Coast'] = 32;
$bits['Canada'] = 64;
$bits['China'] = 128;
$bits['India'] = 256;
$bits['Europe'] = 512;
$bits['South_America'] = 1024;
$bits['Other'] = 2048;

$value = 3;

foreach($bits as $key=>$mask)
{
if(($value & $mask) <> 0)
{
echo "$key was set<br />";
}
}
?>