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
Live24x7
Forum Contributor
Posts: 194 Joined: Sat Nov 19, 2011 9:32 am
Post
by Live24x7 » Tue Oct 16, 2012 10:43 am
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
Christopher
Site Administrator
Posts: 13596 Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US
Post
by Christopher » Tue Oct 16, 2012 11:55 am
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
Post
by Live24x7 » Tue Oct 16, 2012 12:34 pm
now that makes sense
Mordred
DevNet Resident
Posts: 1579 Joined: Sun Sep 03, 2006 5:19 am
Location: Sofia, Bulgaria
Post
by Mordred » Tue Oct 16, 2012 2:26 pm
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
Post
by Live24x7 » Tue Oct 16, 2012 3:22 pm
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 ?
Mordred
DevNet Resident
Posts: 1579 Joined: Sun Sep 03, 2006 5:19 am
Location: Sofia, Bulgaria
Post
by Mordred » Tue Oct 16, 2012 4:49 pm
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
Post
by Live24x7 » Tue Oct 16, 2012 5:29 pm
thanks a lot !