How to see binary representation of variable

前端 未结 7 1306
醉梦人生
醉梦人生 2020-12-19 00:07

Is there any possibility to see binary representation of variable?

相关标签:
7条回答
  • 2020-12-19 00:16

    decbin(your_int) will return a string in binary numbers representing the same value as your_int, assuming that's what you're asking for.

    0 讨论(0)
  • 2020-12-19 00:17
    $a = 42;
    for($i = 8 * PHP_INT_SIZE - 1; $i >= 0; $i --) {
        echo ($a >> $i) & 1 ? '1' : '0';
    }
    
    0 讨论(0)
  • 2020-12-19 00:18
    <?php
    /**
     *    Returns an ASCII string containing
     *    the binary representation of the input data .
    **/
    function str2bin($str, $mode=0) {
        $out = false;
        for($a=0; $a < strlen($str); $a++) {
            $dec = ord(substr($str,$a,1));
            $bin = '';
            for($i=7; $i>=0; $i--) {
                if ( $dec >= pow(2, $i) ) {
                    $bin .= "1";
                    $dec -= pow(2, $i);
                } else {
                    $bin .= "0";
                }
            }
            /* Default-mode */
            if ( $mode == 0 ) $out .= $bin;
            /* Human-mode (easy to read) */
            if ( $mode == 1 ) $out .= $bin . " ";
            /* Array-mode (easy to use) */
            if ( $mode == 2 ) $out[$a] = $bin;
        }
        return $out;
    }
    ?>
    

    Copied from: http://php.net/manual/en/ref.strings.php

    0 讨论(0)
  • 2020-12-19 00:20

    Or you may use base_convert function to convert symbol codes to binary, here's a modified function:

    function str2bin($str) 
    {
        $out=false; 
        for($a=0; $a < strlen($str); $a++)
        {
            $dec = ord(substr($str,$a,1)); //determine symbol ASCII-code
            $bin = sprintf('%08d', base_convert($dec, 10, 2)); //convert to binary representation and add leading zeros
            $out .= $bin;
        }
        return $out;
    }
    

    It is useful to convert inet_pton() result to compare ipv6 addresses in binary format (since you cannot really convert a 128-bit ipv6 address to integer, which is 32- or 64-bit in php). You can find more on ipv6 and php here (working-with-ipv6-addresses-in-php) and here (how-to-convert-ipv6-from-binary-for-storage-in-mysql).

    0 讨论(0)
  • 2020-12-19 00:24

    Like so:

    echo decbin(3); // 11
    
    0 讨论(0)
  • 2020-12-19 00:24

    What about: <?php $binary = (binary) $string; $binary = b"binary string"; ?>

    (from php.net)

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