Is there any possibility to see binary representation of variable?
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.
$a = 42;
for($i = 8 * PHP_INT_SIZE - 1; $i >= 0; $i --) {
echo ($a >> $i) & 1 ? '1' : '0';
}
<?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
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).
Like so:
echo decbin(3); // 11
What about: <?php
$binary = (binary) $string;
$binary = b"binary string";
?>
(from php.net)