Whats with this piece of code

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Live24x7
Forum Contributor
Posts: 194
Joined: Sat Nov 19, 2011 9:32 am

Whats with this piece of code

Post 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
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Whats with this piece of code

Post 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.
(#10850)
Live24x7
Forum Contributor
Posts: 194
Joined: Sat Nov 19, 2011 9:32 am

Re: Whats with this piece of code

Post by Live24x7 »

now that makes sense :)
User avatar
Mordred
DevNet Resident
Posts: 1579
Joined: Sun Sep 03, 2006 5:19 am
Location: Sofia, Bulgaria

Re: Whats with this piece of code

Post by Mordred »

The first expression would tell you if $x is odd or even
Live24x7
Forum Contributor
Posts: 194
Joined: Sat Nov 19, 2011 9:32 am

Re: Whats with this piece of code

Post 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 ?
User avatar
Mordred
DevNet Resident
Posts: 1579
Joined: Sun Sep 03, 2006 5:19 am
Location: Sofia, Bulgaria

Re: Whats with this piece of code

Post 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
Live24x7
Forum Contributor
Posts: 194
Joined: Sat Nov 19, 2011 9:32 am

Re: Whats with this piece of code

Post by Live24x7 »

thanks a lot !
Post Reply