简体   繁体   English

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

[英]Convert binary to hexadecimal using PHP

How do I convert a binary number (ie 1111111 ) to hexadecimal (ie 7f ) using PHP?如何使用 PHP 将二进制数(即1111111 )转换为十六进制数(即7f )? I recognize I could do dechex(bindec('1111111'));我知道我可以做dechex(bindec('1111111')); , however, I am certain that this is not the right way.但是,我确信这不是正确的方法。

I tried bin2hex('1111111') but it resulted in 31313131313131.我试过bin2hex('1111111')但结果是 31313131313131。

Your solution is fine.你的解决方案很好。 You can also use base_convert .您也可以使用base_convert

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

But keep in mind that php is not built for calculations.但请记住,php 不是为计算而构建的。 It is built for working with strings.它是为处理字符串而构建的。

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参考: 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查看此链接以获取更多信息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;
 }

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM