Convert binary to hexadecimal using PHP

前端 未结 4 1677
鱼传尺愫
鱼传尺愫 2021-01-28 15:06

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

相关标签:
4条回答
  • 2021-01-28 15:15
    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

    0 讨论(0)
  • 2021-01-28 15:16

    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

    0 讨论(0)
  • 2021-01-28 15:20

    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;
     }
    
    ?>
    
    0 讨论(0)
  • 2021-01-28 15:21

    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.

    0 讨论(0)
提交回复
热议问题