note 90514 added to language.operators.bitwise

From: Date: Sun, 26 Apr 2009 07:19:57 +0000
Subject: note 90514 added to language.operators.bitwise
Groups: php.notes 
Request: Send a blank email to php-notes+get-153776@lists.php.net to get a copy of this message
Here is an easy way to use bitwise operation for 'flag' functionality. By this I mean managing a set of options which can either be ON or OFF, where zero or more of these options may be set and each option may only be set once. (If you are familiar with MySQL, think 'set' datatype). Note: to older programmers, this will be obvious. Here is the code: <?php function set_bitflag(/*variable-length args*/) { $val = 0; foreach(func_get_args() as $flag) $val = $val | $flag; return $val; } function is_bitflag_set($val, $flag) { return (($val & $flag) === $flag); } // Define your flags define('MYFLAGONE', 1); // 0001 define('MYFLAGTWO', 2); // 0010 define('MYFLAGTHREE', 4); // 0100 define('MYFLAGFOUR', 8); // 1000 ?> I should point out: your flags are stored in a single integer. You can store loads of flags in a single integer. To use my functions, say you wanted to set MYFLAGONE and MYFLAGTHREE, you would use: <?php $myflags = set_bitflags(MYFLAGONE, MYFLAGTHREE); ?> Note: you can pass set_bitflags() as many flags to set as you want. When you want to test later if a certain flag is set, use e.g.: <?php if(is_bitflag_set($myflags, MYFLAGTWO)) { echo "MYFLAGTWO is set!"; } ?> The only tricky part is defining your flags. Here is the process: 1. Write a list of your flags 2. Count them 3. Define the last flag in your list as 1 times 2 to the power of <count> minus one. ( I.E. 1*2^(<count>-1) ) 3. Working backwards through your list, from the last to the first, define each one as half of the previous one. You should reach 1 when you get to the first If you want to understand binary numbers, bits and bitwise operation better, the wikipedia page explains it well - http://en.wikipedia.org/wiki/Bitwise_operation. ---- Server IP: 117.55.229.1 Probable Submitter: 58.96.44.86 ---- Manual Page -- http://www.php.net/manual/en/language.operators.bitwise.php Edit -- https://master.php.net/note/edit/90514 Del: integrated -- https://master.php.net/note/delete/90514/integrated Del: useless -- https://master.php.net/note/delete/90514/useless Del: bad code -- https://master.php.net/note/delete/90514/bad+code Del: spam -- https://master.php.net/note/delete/90514/spam Del: non-english -- https://master.php.net/note/delete/90514/non-english Del: in docs -- https://master.php.net/note/delete/90514/in+docs Del: other reasons-- https://master.php.net/note/delete/90514 Reject -- https://master.php.net/note/reject/90514 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#153776) next »