【发布时间】:2011-08-07 23:54:30
【问题描述】:
有没有可能看到变量的二进制表示?
【问题讨论】:
-
您到底想看什么? base2 中的数字?
标签: php
有没有可能看到变量的二进制表示?
【问题讨论】:
标签: php
像这样:
echo decbin(3); // 11
【讨论】:
另一种解决方案:
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
【讨论】:
$n = PHP_INT_SIZE * 8;
decbin(your_int) 将返回一个二进制数字字符串,表示与your_int 相同的值,假设这就是您所要求的。
【讨论】:
<?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;
}
?>
【讨论】:
或者你可以使用 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) 上找到更多信息。
【讨论】:
$a = 42;
for($i = 8 * PHP_INT_SIZE - 1; $i >= 0; $i --) {
echo ($a >> $i) & 1 ? '1' : '0';
}
【讨论】:
怎么样:<?php
$binary = (binary) $string;
$binary = b"binary string";
?>
(来自php.net)
【讨论】: