如何查看变量的二进制表示

时间:2011-04-18 15:31:48

标签: php

是否有可能看到变量的二进制表示?

7 个答案:

答案 0 :(得分:7)

另一种解决方案:

function d2b($dec, $n = 16) {
    return str_pad(decbin($dec), $n, "0", STR_PAD_LEFT);
}

示例:

// example:
echo d2b(E_ALL);
echo d2b(E_ALL | E_STRICT);
echo d2b(0xAA55);
echo d2b(5);

Output:
0111011111111111
0111111111111111
1010101001010101
0000000000000101

答案 1 :(得分:6)

像这样:

echo decbin(3); // 11

答案 2 :(得分:5)

decbin(your_int)将返回一个二进制数字符串,表示与your_int相同的值,假设这就是您所要求的。

答案 3 :(得分:3)

<?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;
}
?>

复制自:http://php.net/manual/en/ref.strings.php

答案 4 :(得分:3)

或者您可以使用base_convert函数将符号代码转换为二进制,这是一个修改过的函数:

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;
}

将inet_pton()结果转换为比较二进制格式的ipv6地址非常有用(因为你无法真正将128位ipv6地址转换为整数,在php中为32位或64位)。 您可以在ipv6和php here (working-with-ipv6-addresses-in-php)以及here (how-to-convert-ipv6-from-binary-for-storage-in-mysql)上找到更多信息。

答案 5 :(得分:2)

$a = 42;
for($i = 8 * PHP_INT_SIZE - 1; $i >= 0; $i --) {
    echo ($a >> $i) & 1 ? '1' : '0';
}

答案 6 :(得分:1)

怎么样:<?php $binary = (binary) $string; $binary = b"binary string"; ?>

(来自php.net