note 84305 deleted from language.operators.bitwise by danielc

From: Date: Mon, 13 Apr 2009 16:13:24 +0000
Subject: note 84305 deleted from language.operators.bitwise by danielc
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-153167@lists.php.net to get a copy of this message
Note Submitter: strata_ranger at hotmail dot com Reason: 0 ---- Quick reminder about an easy gotcha: When using the ~ operator on variables make sure you know what the variable's type is -- typecast when unsure. I learned this the hard way when using the ~ and & operators to test bits in an integer context, without realizing that one of my variables was actually initialized as a string: <?php $foo = 0; // $foo is int $bar = '0'; // $bar is string . . . // This works if (~$foo & 0x20) { ... } // This doesn't work if (~$bar & 0x20) { ... } ?> The first case is straightforward; the second case is a little more underhanded: - ($bar) is string, so the ~ operator will use its ASCII value, 0x30 - (~$bar) returns ASCII character 0xFFCF (on 32-bit systems) - (0x20) is an integer, so the & operator will use integer values - (~$bar) is not a number, so its integer value is zero - (~$bar & 0x20) equals zero In my case the variable was a class member initialized from an include()'d file, so it took a good while to hunt down....

« previous php.notes (#153167) next »