note 57036 added to language.operators.bitwise
| From: | junk at spheresys dot com | Date: | Thu, 22 Sep 2005 06:25:42 +0000 |
| Subject: | note 57036 added to language.operators.bitwise | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-95576@lists.php.net to get a copy of this message | ||
I wanted to print a binary representation of an integer here it is
<?php
function binString($var, $safety = 0) {
return ($var & 1) . ($var != 0 && $safety < 31 ? binString($var >> 1,
$safety+1) : "");
}
print binString(5); // would print 101
print binString(15); // would print 1111
?>
Explanation:
the first expression after the return statement will evaluate to 1 or 0 according to the least
significant bit.
then we have our stop condition if there is still non zero bits left or if we are at the 32nd bit
otherwise we call recursively on to the n-1 bits (by shifting out the least significant bit).
----
Manual Page -- http://www.php.net/manual/en/language.operators.bitwise.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+57036
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+57036&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+57036&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+57036&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+57036&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+57036&report=yes&reason=non-english
Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+57036&report=yes&reason=already+in+docs
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+57036&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+57036&report=yes
Search -- http://master.php.net/manage/user-notes.php