How do I convert a binary number (i.e. 1111111
) to hexadecimal (i.e. 7f
) using PHP? I recognize I could do dechex(bindec(\'1111111\'));
, h
dechex(bindec($binary));
It is the right way, you are putting extra ")"(Closing Parenthesis) in the end...
Reference: http://php.net/manual/en/function.bin2hex.php
try this:
<?php
$binary = "11111001";
$hex = dechex(bindec($binary));
echo $hex;
?>
look at this link for more info http://php.net/manual/en/function.bin2hex.php
You can also try this function:
<?php
function hexentities($str) {
$return = '';
for($i = 0; $i < strlen($str); $i++) {
$return .= '&#x'.bin2hex(substr($str, $i, 1)).';';
}
return $return;
}
?>
Your solution is fine. You can also use base_convert.
$binary = '1111111';
echo base_convert($binary, 2, 16); // 7f
But keep in mind that php is not built for calculations. It is built for working with strings.