[nycphp-talk] Bitwise Operators

Hans Zaunere lists at
Wed Jun 29 12:13:23 EDT 2005

> Years ago (back in the '80s), hardware was expensive.  Memory and disk
> storage were at a premium.  When we wrote programs, we kept efficiency
> in mind.  Using bits to set/clear flags, we could get 8 flags using only
> one byte of storage.  Today it seems ridiculous to do things like that,
> when a boolean variable will do, but at that time computers were slow
> and expensive.  I don't see as much value to bit operations today as I
> did in the past.

I used to be a big fan of masks and bits.   But you're absolutely right that they've lost a lot of use.  One of the few places they're still seen regularly is in IP addresses and netmasks.  That said, of course, if this was New York Embedded Systems or New York Assembler, instead of New York PHP, we'd probably have a different viewpoint.

I do still use them at times in PHP, especially for flags.  For instance, they can be real handy - and REAL fast - for storing multiple values in a single column.

define('USER_ATTRIB_SU', 1024);
define('USER_ATTRIB_BAN', 2048);

mysql_query("INSERT INTO UserTable (UserID,Attributes)
             VALUES ('500','".USER_ATTRIB_SU."')",$MYDB);

mysql_query("UPDATE UserTable
                SET Attributes = Attributes | '".USER_ATTRIB_BAN."'           
              WHERE UserID='500'",$MYDB);

/*** Now get all users that are super users ***/

mysql_query("SELECT UserID FROM UserTable
              WHERE Attributes & '".USER_ATTRIB_SU."' = '".USER_ATTRIB_SU."'",$MYDB);

There's an elegance to using them that is nice, instead of StudelyCaps and <TAG>Verbose Tags</TAG>

Hans Zaunere
President, Founder

New York PHP

AMP Technology
Supporting Apache, MySQL and PHP

More information about the talk mailing list