downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

ceil> <base_convert
[edit] Last updated: Fri, 25 May 2012

view this page in

bindec

(PHP 4, PHP 5)

bindec2 進数 を 10 進数に変換する

説明

number bindec ( string $binary_string )

引数 binary_string により指定された 2 進数と等価な 10 進数を返します。

bindec() は、2 進数を integer に変換します。 サイズの問題により、必要に応じて float となることもあります。

bindec() は、すべての binary_string 値を符号なし整数として扱います。 これは、bindec() が最上位ビットを 符号ビットとしてではなく規模をはかるためのに使用するからです。

パラメータ

binary_string

変換したい 2 進数文字列。

警告

このパラメータは文字列でなければなりません。 他のデータ型を使用すると、予期せぬ結果となります。

返り値

binary_string を 10 進に変換した値を返します。

変更履歴

バージョン 説明
Since 4.1.0 この関数は、integer 型の範囲をこえる大きな数値も変換できるようになりました。 そのような値は、float で返します。

例1 bindec() の例

<?php
echo bindec('110011') . "\n";
echo 
bindec('000110011') . "\n";

echo 
bindec('111');
?>

上の例の出力は以下となります。

51
51
7

例2 bindec() が入力を符号なし整数として処理する例

<?php
/*
 * The lesson from this example is in the output
 * rather than the PHP code itself.
 */

$magnitude_lower pow(2, (PHP_INT_SIZE 8) - 2);
p($magnitude_lower 1);
p($magnitude_lower'See the rollover?  Watch it next time around...');

p(PHP_INT_MAX'PHP_INT_MAX');
p(~PHP_INT_MAX'interpreted to be one more than PHP_INT_MAX');

if (
PHP_INT_SIZE == 4) {
    
$note 'interpreted to be the largest unsigned integer';
} else {
    
$note 'interpreted to be the largest unsigned integer
              (18446744073709551615) but skewed by float precision'
;
}
p(-1$note);


function 
p($input$note '') {
    echo 
"input:        $input\n";

    
$format '%0' . (PHP_INT_SIZE 8) . 'b';
    
$bin sprintf($format$input);
    echo 
"binary:       $bin\n";

    
ini_set('precision'20);  // For readability on 64 bit boxes.
    
$dec bindec($bin);
    echo 
'bindec():     ' $dec "\n";

    if (
$note) {
        echo 
"NOTE:         $note\n";
    }

    echo 
"\n";
}
?>

上の例の 32 ビットマシンでの出力は、このようになります。

input:        1073741823
binary:       00111111111111111111111111111111
bindec():     1073741823

input:        1073741824
binary:       01000000000000000000000000000000
bindec():     1073741824
NOTE:         See the rollover?  Watch it next time around...

input:        2147483647
binary:       01111111111111111111111111111111
bindec():     2147483647
NOTE:         PHP_INT_MAX

input:        -2147483648
binary:       10000000000000000000000000000000
bindec():     2147483648
NOTE:         interpreted to be one more than PHP_INT_MAX

input:        -1
binary:       11111111111111111111111111111111
bindec():     4294967295
NOTE:         interpreted to be the largest unsigned integer

上の例の 64 ビットマシンでの出力は、このようになります。

input:        4611686018427387903
binary:       0011111111111111111111111111111111111111111111111111111111111111
bindec():     4611686018427387903

input:        4611686018427387904
binary:       0100000000000000000000000000000000000000000000000000000000000000
bindec():     4611686018427387904
NOTE:         See the rollover?  Watch it next time around...

input:        9223372036854775807
binary:       0111111111111111111111111111111111111111111111111111111111111111
bindec():     9223372036854775807
NOTE:         PHP_INT_MAX

input:        -9223372036854775808
binary:       1000000000000000000000000000000000000000000000000000000000000000
bindec():     9223372036854775808
NOTE:         interpreted to be one more than PHP_INT_MAX

input:        -1
binary:       1111111111111111111111111111111111111111111111111111111111111111
bindec():     18446744073709551616
NOTE:         interpreted to be the largest unsigned integer
              (18446744073709551615) but skewed by float precision

参考

  • decbin() - 10 進数を 2 進数に変換する
  • octdec() - 8 進数を 10 進数に変換する
  • hexdec() - 16 進数を 10 進数に変換する
  • base_convert() - 数値の基数を任意に変換する



ceil> <base_convert
[edit] Last updated: Fri, 25 May 2012
 
add a note add a note User Contributed Notes bindec
info at rickdg dot nl 31-Mar-2010 10:40
Two functions to convert 16bit or 8bit binary to integer using two's complement. If input exceeds maximum bits, false is returned. Function is easily scalable to x bits by changing the hexadecimals.

<?php function _bin16dec($bin) {
   
// Function to convert 16bit binary numbers to integers using two's complement
   
$num = bindec($bin);
    if(
$num > 0xFFFF) { return false; }
    if(
$num >= 0x8000) {
        return -((
$num ^ 0xFFFF)+1);
    } else {
        return
$num;
    }
}

function
_bin8dec($bin) {
   
// Function to convert 8bit binary numbers to integers using two's complement
   
$num = bindec($bin);
    if(
$num > 0xFF) { return false; }
    if(
$num >= 0x80) {
        return -((
$num ^ 0xFF)+1);
    } else {
        return
$num;
    }
}
?>
Nitrogen 21-Jul-2009 01:27
Binary to Decimal conversion using the BCMath extension..

<?php

function BCBin2Dec($Input='') {
 
$Output='0';
  if(
preg_match("/^[01]+$/",$Input)) {
    for(
$i=0;$i<strlen($Input);$i++)
     
$Output=BCAdd(BCMul($Output,'2'),$Input{$i});
  }
  return(
$Output);
}

?>

This will simply convert from Base-2 to Base-10 using BCMath (arbitrary precision calculation).

See also: my 'BCDec2Bin' function on the 'decbin' document.
Enjoy,
Nitrogen.
nodarinodo at mail dot ru 08-Jan-2009 04:51
<?php   
// bindecfunc :)))) I think it works well too :)
function bindecc($str)
    {
       
$str = str_replace(" ", "", $str);
       
$strr = preg_match('/[^01]/', $str);
        if(
$strr == 1) { return "<b> Error ! only 1 and 0;</b>"; }
       
$strsig = strlen($str);
       
$strr1 = strrev($str);
       
$strf = '';
        for(
$i = $strsig; $i >= 0; $i--)
        {
           
$strf += ($strr1[$i] * pow(2, $i));
           
#$strf += $str[$i];
       
}
        return
$strf;
    }
?>
flashpack at gmail dot com 15-Nov-2008 09:40
for converting fractions :
eg : 1001.1101

<?php
function BinaryToDecimal($binary){
 
$binary=trim($binary);
  if (
strstr($binary,'.')){
   
$split=explode('.',$binary);
   
$integer=$split[0];
   
$fraction=$split[1];

   
$digits=str_split($fraction);
   
$num=sizeof($digits);
    for (
$i=1; $i<=$num;$i++){
      if (
$digits[$i-1]>1){
        echo
'<script>alert("Enter Binary Digits Only {0,1}\n \n eg: 11001 or 11001.011");history.go(-1)</script> ';
      }
     
$exponent=pow(2,-$i);
     
$fraction_result+=$digits[$i-1]*$exponent;
    }

  }else{
   
$integer=$binary;
  }

 
$splits=str_split($integer);
 
$num=sizeof($splits)-1;
 
$i=$num;
  foreach(
$splits as $digits){
    if (
$digits>1){
      echo
'<script>alert("Enter Binary Digits Only {0,1}\n \n eg: 11001 or 11001.011");history.go(-1)</script> ';
    }
   
$exponent=pow(2,$i);
   
$integer_result+=$digits*$exponent;
   
$i--;
  }
  if(
$fraction_result){
   
$result=$integer_result+$fraction_result;
  }else {
   
$result=$integer_result;
  }
  return
$result ;
}
?>
mashematician at gmail dot com 13-Mar-2008 02:57
A binary to decimal conversion function that takes advantage of the BC library functions to return decimal values of arbitrary length.

Input type must be a string in order to work properly.

<?php

function binary_to_decimal($a) {
   
$bin_array = str_split($a);

   
$y=sizeof($bin_array)-1;
    for (
$x=0; $x<sizeof($bin_array)-1; $x++) {
        if (
$bin_array[$x] == 1) {
           
$bin_array[$x] = bcpow(2, $y);
        }
       
$y--;
    }
   
    for (
$z=0; $z<sizeof($bin_array); $z++) {
       
$result = bcadd($result, $bin_array[$z]);
    }
    echo
$result;
}

binary_to_decimal('11111');

?>
alan hogan dot com slash contact 08-Nov-2007 06:34
The "smartbindec" function I wrote below will convert any binary string (of a reasonable size) to decimal.  It will use two's complement if the leftmost bit is 1, regardless of bit length.  If you are getting unexpected negative answers, try zero-padding your strings with sprintf("%032s", $yourBitString).

<?php
function twoscomp($bin) {
   
$out = "";
   
$mode = "init";
    for(
$x = strlen($bin)-1; $x >= 0; $x--) {
        if (
$mode != "init")
           
$out = ($bin[$x] == "0" ? "1" : "0").$out;
        else {
            if(
$bin[$x] == "1") {
               
$out = "1".$out;
               
$mode = "invert";
            }
            else
               
$out = "0".$out;
        }
    }
    return
$out;
}
function
smartbindec($bin) {
    if(
$bin[0] == 1)
        return -
1 * bindec(twoscomp($bin));
    else return (int)
bindec($bin);
}
?>
gwbdome at freenet dot de 19-Aug-2004 08:43
i think a better method than the "shift-method" is my method ^^...
here it comes:

function convert2bin($string) {
     $finished=0;
     $base=1;
     if(preg_match("/[^0-9]/", $string)) {
         for($i=0; $string!=chr($i); $i++);
         $dec_nr=$i;
     }
     else $dec_nr=$string;
     while($dec_nr>$base) {
         $base=$base*2;
         if($base>$dec_nr) {
             $base=$base/2;
             break;
         }
     }
     while(!$finished) {
         if(($dec_nr-$base)>0) {
             $dec_nr=$dec_nr-$base;
             $bin_nr.=1;
             $base=$base/2;
         }
         elseif(($dec_nr-$base)<0) {
             $bin_nr.=0;
             $base=$base/2;
         }
         elseif(($dec_nr-$base)==0) {
             $bin_nr.=1;
             $finished=1;
             while($base>1) {   
                 $bin_nr.=0;
                 $base=$base/2;
             }
         }
     }
     return $bin_nr;
 }

=====================================================

if you want to reconvert it (from binary to string or integer) you can use this function:

function reconvert($bin_nr) {
     $base=1;
     $dec_nr=0;
     $bin_nr=explode(",", preg_replace("/(.*),/", "$1", str_replace("1", "1,", str_replace("0", "0,", $bin_nr))));
     for($i=1; $i<count($bin_nr); $i++) $base=$base*2;
     foreach($bin_nr as $key=>$bin_nr_bit) {
         if($bin_nr_bit==1) {
             $dec_nr+=$base;
             $base=$base/2;
         }
         if($bin_nr_bit==0) $base=$base/2;
     }
     return(array("string"=>chr($dec_nr), "int"=>$dec_nr));
 }
martin at punix dot de 29-May-2003 04:47
## calculate binary with "shift-method" ##

<?php
function dec2bin($decimal_code){
 for(
$half=($decimal_code);$half>=1;$half=(floor($half))/2){
   if((
$half%2)!=0){
   
$y.=1;
   }
   else{
   
$y.=0;
   }
  }
 
$calculated_bin=strrev($y);
 return
$calculated_bin;
}
?>

## example ##

[bin] 123 = [dec] 1111011

e.g.
123/2 = 61,5 => 1
61/2  = 30,5 => 1
30/2  = 15   => 0
15/2  = 7,5  => 1
7/2   = 3,5  => 1
3/2   = 1,5  => 1
1/2   = 0,5  => 1
(0/2   = 0    finish)
php at silisoftware dot com 28-Feb-2002 12:16
For converting larger-than-31-bit numbers:

<?php
function Bin2Dec($binstring) {
    for (
$i=0;$i<strlen($binstring);$i++) {
       
$decvalue += ((int) substr($binstring, strlen($binstring) - $i - 1, 1)) * pow(2, $i);
    }
    return
$decvalue;
}
?>

 
show source | credits | stats | sitemap | contact | advertising | mirror sites