note 80634 deleted from language.operators.bitwise by danielc
| From: | danielc@php.net | Date: | Mon, 13 Apr 2009 16:09:56 +0000 |
| Subject: | note 80634 deleted from language.operators.bitwise by danielc | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-153152@lists.php.net to get a copy of this message | ||
Note Submitter: ironiridis at gmail dot com
Reason: 0
----
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.