PHP Bitmask Utility

While working on a small project for WITS, the technical services department at Willamette University, I put together this bitmasking tool for easily managing enumerable data in PHP. I googled around for a little bit before building this, but all the tools I found seemed overly complex without providing any better functionality.

To use this tool, you simply construct an instance of bitmasker, passing it a description of the data you wish to encode, and then can use the defined methods to convert array data into masks, and masks back into array data again. Bitmasker can work with masks of any size, it is not limited to 32bits, however if the mask is smaller than 32 bits, Bitmasker can additionally translate masks into integers and back again for even more efficient storage.


This is a short sample of what we can do with Bitmasker, using unix file permissions as an example:

<?php // we first construct the mask $filePerm = new bitmasker(array('exec','write','read')); // now we want to create a bitmask of only read permission: $intVal = $filePerm->arrayToIntMask(array('read')); echo $intVal; // returns 4 // returns true if 'read' is set on this mask, which it is echo $filePerm->getValue($mask,'read'); // create a new mask based off our old one, with exec on too $newMask = $filePerm->setIndex($mask,'exec',true); // returns true since exec is now also set echo $filePerm->getValue($newMask,'exec'); ?>

Download: Bitmasker Class
Size: 3.58kb