Page 1 of 1

Whats with this piece of code

Posted: Tue Oct 16, 2012 10:43 am
by Live24x7
Can someone pls explain what does these two lines of code mean:

Code: Select all

$y = (bool) ($x & 0x01);
            $x >>= 1;
More specifically,

1) What is the meaning of (bool) ($x & 0x01);
I know bool would convert a string to boolean but what does ($x & 0x01) mean ?

2) what does this symbol >>= in the 2nd line mean ?


Thanks a lot

Re: Whats with this piece of code

Posted: Tue Oct 16, 2012 11:55 am
by Christopher
You don't see that too often in PHP. Those are bitwise operators (http://us1.php.net/manual/en/language.o ... itwise.php).

(bool) ($x & 0x01) would cast to a boolean the value bitwise ANDed with 1 -- so it would either be 0 or 1.

$x >>= 1; would shift bits to the right 1 place which is the same as dividing by 2.

Re: Whats with this piece of code

Posted: Tue Oct 16, 2012 12:34 pm
by Live24x7
now that makes sense :)

Re: Whats with this piece of code

Posted: Tue Oct 16, 2012 2:26 pm
by Mordred
The first expression would tell you if $x is odd or even

Re: Whats with this piece of code

Posted: Tue Oct 16, 2012 3:22 pm
by Live24x7
i tried this out and it indeed returns 1 for all odd numbers and Null for all even numbers...
but i did not quite get the logic ..


when someone says ($x & 0x01) does it mean adding binary 1(00000001) to the ASCII equivalent of $x or what is it ?

Re: Whats with this piece of code

Posted: Tue Oct 16, 2012 4:49 pm
by Mordred
It's not *adding*, it's AND-ing.
Any bit ANDed with 0 becomes 0
Any bit ANDed with 1 remains unchanged
AND-ing a number with ..0001 will zero all its bits but the last one
The last bit in a binary number shows whether the number is odd or even

Re: Whats with this piece of code

Posted: Tue Oct 16, 2012 5:29 pm
by Live24x7
thanks a lot !