使用 PHP 将二进制转换为十六进制

Convert binary to hexadecimal using PHP

如何使用 PHP 将二进制数(即 1111111)转换为十六进制数(即 7f)?我知道我可以做到 dechex(bindec('1111111'));,但是,我确定这不是正确的方法。

我尝试了 bin2hex('1111111'),但结果是 31313131313131。

dechex(bindec($binary));

这是正确的方法,你在最后添加了额外的")"(右括号)...

参考:http://php.net/manual/en/function.bin2hex.php

你的解决方案很好。您也可以使用 base_convert.

$binary = '1111111';
echo base_convert($binary, 2, 16); // 7f

但请记住,php 不是为计算而构建的。它专为处理字符串而构建。

试试这个:

<?php
$binary = "11111001";
$hex = dechex(bindec($binary));
echo $hex;
?>

查看此 link 了解更多信息 http://php.net/manual/en/function.bin2hex.php

你也可以试试这个功能:

<?php

function hexentities($str) {
$return = '';
for($i = 0; $i < strlen($str); $i++) {
    $return .= '&#x'.bin2hex(substr($str, $i, 1)).';';
}
return $return;
 }

?>