2011-04-18 20 views

回答

6

像這樣:

echo decbin(3); // 11 
5

decbin(your_int)將返回一個二進制數字的字符串,表示與your_int相同的值,假設這就是您要求的。

2
<?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

+0

用decbin()替換內部循環會更容易,或者至少使用位移而不是指數函數。 – 2011-04-18 15:46:27

+0

是的,我也注意到了。這不是我從php網站複製的我的代碼。 – 2011-04-18 16:05:19

1

什麼:<?php $binary = (binary) $string; $binary = b"binary string"; ?>

(從php.net

+0

這不會以二進制表示形式顯示字符串,它僅將文字字符串「轉換」(或轉換)爲二進制字符串。 – 2011-04-19 09:47:38

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地址爲整數,這是32位或64位的有用PHP)。 你可以找到更多關於ipv6和php here (working-with-ipv6-addresses-in-php)here (how-to-convert-ipv6-from-binary-for-storage-in-mysql)

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 
2
$a = 42; 
for($i = 8 * PHP_INT_SIZE - 1; $i >= 0; $i --) { 
    echo ($a >> $i) & 1 ? '1' : '0'; 
}