Zend - The PHP Company




Miscellaneous

Add Code


Bit manipulation  

Type: code fragment
Added by: maniac
Entered: 27/03/2000
Last modified: 08/12/1999
Rating: **** (9 votes)
Views: 9056
If you need to keep track of a lot of on/off toggles, like user settings etc. There is only one easy way to store and manipulate these values: Bitfields. With these functions manipulating bitfields becomes easy. Everything you need is included below.


<?php
/* Functions for manipulating BITFIELDS
 *
 * init_bit(            bitfield        );
 * query_bit(           bitfield, bit   );
 * set_bit(             bitfield, bit   );
 * remove_bit(          bitfield, bit   );
 * toggle_bit(          bitfield, bit   );
 *
 */

/* Some handy bitvalues, easy to remember */
define"BIT_0");
define"BIT_1");
define"BIT_2");
define"BIT_3");
define"BIT_4");
define"BIT_5"16 );
define"BIT_6"32 );
define"BIT_7"64 );
define"BIT_8"128 );
define"BIT_9"256 );
define"BIT_10"512 );
define"BIT_11"1024 );
define"BIT_12"2048 );
define"BIT_13"4096 );
define"BIT_14"8192 );
define"BIT_15"16384 );
define"BIT_16"32768 );
define"BIT_17"65536 );
define"BIT_18"131072 );
define"BIT_19"262144 );
define"BIT_20"524288 );
define"BIT_21"1048576 );
define"BIT_22"2097152 );
define"BIT_23"4194304 );
define"BIT_24"8388608 );
define"BIT_25"16777216 );
define"BIT_26"33554432 );
define"BIT_27"67108864 );
define"BIT_28"134217728 );
define"BIT_29"268435456 );
define"BIT_30"536870912 );
define"BIT_31"1073741824 );

/* Because of a bug in PHP we need this init function,
 * it's a workaround for the bug. If you want to know if
 * this bug has been fixed, check bugs.php.net, bugid: 3176
 * So, best is to use this simple init every time you
 * create a new bitfield variable.
 */

function init_bit( &$bitfield )
{
    
$bitfield = ($bitfield 0);
}


/* Return true or false, depending on if the bit is set */
function query_bit$bitfield$bit )
{
        return ( 
$bitfield $bit );
}

/* Force a specific bit(pattern) to ON */
function set_bit( &$bitfield$bit )
{
        
$bitfield |= $bit;
}

/* Force a specific bit(pattern) to be OFF */
function remove_bit( &$bitfield$bit )
{
        
$bitfield &= ~$bit;
}

/* Toggle a bit(pattern), so bits that are on are turned off, and bits that are off are turned on. */
function toggle_bit( &$bitfield$bit )
{
        
$bitfield ^= $bit;
}


?>


Usage Example


$bitfield = 0;
bit_init( $bitfield );

set_bit( $bitfield, BIT_10 )
toggle_bit( $bitfield, BIT_11 )

query_bit( $bitfield, BIT_10) -> true
query_bit( $bitfield, BIT_11) -> true
query_bit( $bitfield, BIT_5 ) -> false


Rate This Script





Search



This Category All Categories