note 40256 added to language.operators.bitwise

From: Date: Thu, 26 Feb 2004 19:11:04 +0000
Subject: note 40256 added to language.operators.bitwise
Groups: php.notes 
Request: Send a blank email to php-notes+get-65821@lists.php.net to get a copy of this message
Here is a useful function for setting flags (or bits). It takes three paramaters: 1. $var This is the variable whose flag you want to set 2. $flag This is the flag(s) you want set 3. $set This is either ON or OFF Simply adding or subtracting a flag is not a good idea. For example, if the variable is in binary 0101 (thats 5 in dec) and you want to turn the 1 bit off subtracttion would work. 5-1=4 which would be 0100. However, the variable is 0100, and you want subtracted, 4-1 =3 or 0011. What you intended to do was to turn off the one bit regardless of whether it is on or off. This function will turn on or off a bit(or bits) regardless of the bit's current state. <?php define('ON', 1); define('OFF', 0); function setflag(&$var, $flag, $set=ON ) { if (($set == ON)) $var = ($var | $flag); if (($set == OFF)) $var = ($var & ~$flag); return; } ?> For a full test of this try this code: <pre> <?php define ('f1', 1); define ('f2', 2); define ('f4', 4); define ('f8', 8); define('ON', 1); define('OFF', 0); function setflag(&$var, $flag, $set=ON ) { if (($set == ON)) $var = ($var | $flag); if (($set == OFF)) $var = ($var & ~$flag); return; } function dbi($var){ // display number as binary (four bits) $output = ($var & f8) ? '1' : '0'; $output .= ($var & f4) ? '1' : '0'; $output .= ($var & f2) ? '1' : '0'; $output .= ($var & f1) ? '1' : '0'; return $output; } $var1 = ( f8 | f2 | f1 ); echo (" " . dbi($var1). "\n" ); echo ("ON " . dbi(f4). "\n" ); setflag($var1, f4, ON); echo ("IS " . dbi($var1). "\n" ); echo ("\n"); $var2 = ( f8 | f2 | f1 ); echo (" " . dbi($var2). "\n" ); echo ("OFF " . dbi(f1). "\n" ); setflag($var2, f1, OFF); echo ("IS " . dbi($var2). "\n" ); echo ("\n"); echo ("\n"); $var3 = ( f8 | f2 | f1 ); echo (" " . dbi($var3). "\n" ); echo ("ON " . dbi((f4 | f1)). "\n" ); setflag($var3, (f4 | f1), ON); echo ("IS " . dbi($var3). "\n" ); echo ("\n"); $var4 = ( f8 | f2 | f1 ); echo (" " . dbi($var4). "\n" ); echo ("OFF " . dbi((f4 | f1)). "\n" ); setflag($var4, (f4 | f1), OFF); echo ("IS " . dbi($var4). "\n" ); echo ("\n"); ?> </pre> Which returns: 1011 ON 0100 IS 1111 1011 OFF 0001 IS 1010 1011 ON 0101 IS 1111 0100 OFF 0101 IS 0000 ---- Manual Page -- http://www.php.net/manual/en/language.operators.bitwise.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+40256 Delete -- http://master.php.net/manage/user-notes.php?action=delete+40256&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+40256&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#65821) next »