I also wished to have the ability to translate a string containing a binary number ('1101') to a string containing a hexadecimal number ('d'). Here is my function:
function strbin2hex($bin){
$last = strlen($bin)-1;
for($i=0; $i<=$last; $i++){ $x += $bin[$last-$i] * pow(2,$i); }
return dechex($x);
}
Example:
strbin2hex('1101'); // returns 'd'
I also added some optional features to my function (zero padding and upper case hex letters):
function strbin2hex($bin, $pad=false, $upper=false){
$last = strlen($bin)-1;
for($i=0; $i<=$last; $i++){ $x += $bin[$last-$i] * pow(2,$i); }
$x = dechex($x);
if($pad){ while(strlen($x) < intval(strlen($bin))/4){ $x = "0$x"; } }
if($upper){ $x = strtoupper($x); }
return $x;
}
Examples:
strbin2hex('11110101', true, true); // returns 'F5'
strbin2hex('00001011', true, true); // returns '0B'