2011-04-18 2 views

답변

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

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

+0

내부 루프를 decbin()으로 대체하거나 지수 함수가 아닌 비트 쉬프트를 사용하는 것이 더 쉽습니다. –

+0

예 나는 또한 그것을 알아 차렸다. PHP 코드를 복사 한 코드가 아닙니다. –

1

무엇에 대해 : 복사

echo decbin(3); // 11 
+0

문자열은 이진 표현으로 표시되지 않으며 리터럴 문자열 만 이진 문자열로 "변환"(또는 형 변환)됩니다. –

3

아니면 기호를 변환하는 기능을 base_convert 사용할 수 있습니다 (php.net에서) 코드를 바이너리로 변환하려면 여기를 클릭하십시오. 에드 기능 :

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

당신이 정말 정수로 128 비트의 IPv6 주소, 32 비트 또는 64 비트에 변환 할 수 없기 때문에 (바이너리 형식으로 IPv6 주소를 비교하는 inet_pton() 결과를 변환하는 데 유용합니다 PHP). ipv6 및 phy 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'; 
} 
관련 문제