note 110275 deleted from function.base-convert by danbrown
| From: | danbrown@php.net | Date: | Wed, 17 Oct 2012 21:26:09 +0000 |
| Subject: | note 110275 deleted from function.base-convert by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-191398@lists.php.net to get a copy of this message | ||
Note Submitter: espertalhao04 at hotmail dot com
----
holdoffhunger at gmail dot com
you have created a great function, although it's really heavy and long.
i have optimized TO ALMOST THE LIMIT your function:
<?php
function hex_bin($hex)
{
$bin=array("0000","0001","0010","0011","0100","0101","0110","0111",
"1000","1001",'a'=>"1010",'b'=>"1011",'c'=>"1100",'d'=>
"1101",'e'=>"1110",'f'=>"1111");
$c = strlen($hex=strtolower($hex));
for($i=0;$i<=$c;$i++)
{
@$o.=$bin[$hex[$i]];
}
return $o;
}
echo hex_bin("1234567890aBcDeF"),PHP_EOL;
/*returns EXACTLY
0001001000110100010101100111100010010000101010111100110111101111*/
?>
why i made this on this way:
1- smaller in disk space, smaller in memory, smaller in lines
2- less vars (7 against 4) and abused them to the limit!
3- the data doesn't need so many verifications, since it's already in memory, always
available
4- less cpu usage: all those verifications hurt the performance sooo badly!!!
it has to do 16 verifications per char, in worst case scenario (if everything is
"fffff...")
my version has to do 0 verifications and the value is already in memory!!!
5- footprint: when the function exits, everything is cleaned, which doesn't happen on your
code, cause you didn't have it inside a function bla(){code}
you could do this all in 1 line, 2 arrays and 1 var (i create a new function for simplicity and to
do more and repeat less):
<?php
function hex_bin($hex)
{
str_replace(
array("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"),
array("0000","0001","0010","0011","0100","0101","0110","0111",
"1000","1001","1010","1011","1100","1101","1110","1111")
,strtolower($hex));
}
echo hex_bin("1234567890aBcDeF"),PHP_EOL;
/*the output is EXACTLY THE SAME as in both versions:
0001001000110100010101100111100010010000101010111100110111101111*/
?>
or you could create your own regex with preg_replace();
this is just an idea!!!
but you had a great idea, i made 2 improvements and gave another idea ;)
if you ask me which variant to use, i would say the second, cause uses less vars and relies on 100%
php internal optimized code.
i didn't has tested the times but this is my opinion!