note 80634 added to language.operators.bitwise
| From: | ironiridis at gmail dot com | Date: | Sat, 26 Jan 2008 09:04:11 +0000 |
| Subject: | note 80634 added to language.operators.bitwise | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-135422@lists.php.net to get a copy of this message | ||
There are some great notes here, but some of them are not as stellar as others. Take a look at the
date they were posted and and replies to them before using them in anything but the most trivial
cases.
For example, any function which uses implicit string to integer casting to evaluate hexadecimal.
This is bad code:
<?php
$integer_a = 41762;
$integer_b = (0+('0x'.dechex($integer_a << 1)));
?>
This is better [but still bad] code:
<?php
$integer_a = 41762;
$integer_b = intval(dechex($integer_a << 1), 16);
?>
This is probably optimal:
<?php
$integer_a = 41762;
$integer_b = (int)$integer_a << 1; // explicit cast
?>
Also, don't re-invent the wheel.
This function is unreadable, [needlessly] recursive, and superfluous:
<?php
function binString($var, $safety = 0) {
return ($var & 1) . ($var != 0 && $safety < 31 ? binString($var >> 1,
$safety+1) : "");
}
print(binString(41762));
?>
This code does the same thing, and it's built-in:
<?php
printf('%b', 41792); // you'd do well to learn about printf()
?>
As always, if there are six ways to do it in C, there are 50 ways to do it in PHP. No method is
wrong as long as it produces the correct result, but only a few methods will upgrade reliably, be
portable, and be readable.
----
Server IP: 209.41.74.194
Probable Submitter: 70.91.178.185
----
Manual Page -- http://www.php.net/manual/en/language.operators.bitwise.php
Edit -- https://master.php.net/note/edit/80634
Del: integrated -- https://master.php.net/note/delete/80634/integrated
Del: useless -- https://master.php.net/note/delete/80634/useless
Del: bad code -- https://master.php.net/note/delete/80634/bad+code
Del: spam -- https://master.php.net/note/delete/80634/spam
Del: non-english -- https://master.php.net/note/delete/80634/non-english
Del: in docs -- https://master.php.net/note/delete/80634/in+docs
Del: other reasons-- https://master.php.net/note/delete/80634
Reject -- https://master.php.net/note/reject/80634
Search -- https://master.php.net/manage/user-notes.php