PHP Classes

File: bitmask_example.php

Recommend this page to a friend!
  Classes of Timm Simpkins   Bitmask Magic   bitmask_example.php   Download  
File: bitmask_example.php
Role: Example script
Content type: text/plain
Description: Example file for bitmask class
Class: Bitmask Magic
Generate bitmasks for storing options.
Author: By
Last change:
Date: 19 years ago
Size: 2,818 bytes


Class file image Download
// Initiate the bitmask class
$bm = new bitmask;

// Create an array of values
// Notice this is backwards from the binary representation. This is because values are
// inserted from right to left by the nature of bitmasks.
$bitmaskarr = array (0,1,0,0,1,0,0,0,1,1,1,0,1,0,1,1,1);

// Insert the array into the class

// Show the mask created from the array
echo $bm->forward_mask . "\n";

// Show the binary representation of the array
echo $bm->bin_mask . "\n";

// This prints the array that was entered. Notice that it is also in reverse order
// from the binary representation.

// Here we can reset the entire contents by inserting our own bitmask
// this mask represents bits 15, 13, 8, and 4 being set

// Example of unsetting bit 13

// Example of setting bit 6

$bm->reverse_mask('0'); // reset the object

// Now a more useful example. (for those not familiar with bitmasks)
// We will create an array of items. Lets say someone purchases a lot of widgets
// with various options. We can create a product code from what they choose and
// convert it back and forth and we can always know solely from that code what
// was purchased. (Yes, I know I don't need these keys, they're just for illustration)

$widgets = array( 0 => 'blue',
1 => 'red',
2 => 'yellow',
3 =>'green',
4 => 'purple',
5 => 'small',
6 => 'medium',
7 => 'large',
8 => 'X-large',
9 => 'hard',
10 => 'soft');
// enter the key values for the options
$bm->assoc_keys = $widgets;

// from a form, you find that the person wants a hard green extra large widget.
// so we enter 10,8, and 3 into our bitmask.
$customer_order = array(10,8,3);
foreach (
$customer_order as $option) {

// Now we have our product code. (1288)
echo $bm->forward_mask;

// If we ever need to convert that product code back to real text, we just have to
// enter it into our class and it gets converted back.

// Get the class to return the options for the widget.

// One final example. Query an individual bit to see if the option is set.

echo $bm->bit_isset(3)?'true':'false';

// bitmasks can also be used for verification of user priveleges, storing user settings in a
// simple fashion, and various other things. Any time you have a list of things that can either
// be true or false, you just have to pull out a bitmask to make life easy.

echo "</pre>";