bindec

(PHP 4, PHP 5, PHP 7, PHP 8)

bindecBinário para decimal

Descrição

bindec(string $binary_string): int|float

Retorna o equivalente decimal do número binário representado pelo argumento binary_string.

bindec() converte um número binário em um int ou, se necessário por questão de tamanho, um float.

bindec() interpreta todos os valores de binary_string como inteiros sem sinal. Isto é devido a bindec() enxergar o bit mais significativo como uma outra ordem de magnitude e não como um bit de sinal.

Parâmetros

binary_string

A string binária a converter. Quaisquer caracteres inválidos em binary_string são silenciosamente ignorados. A partir do PHP 7.4.0, fornecer qualquer caractere inválido está defasado.

Aviso

O parâmetro deve ser uma string. Usar outros tipos de dados produzirá resultados inesperados.

Valor Retornado

O valor decimal de binary_string

Registro de Alterações

Versão Descrição
7.4.0 Passar caracteres inválidos agora irá gerar uma nota de defasagem. O resultado ainda será computado como se os caracteres inválidos não existissem.

Exemplos

Exemplo #1 Exemplo de bindec()

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

echo
bindec('111');
?>

O exemplo acima produzirá:

51
51
7

Exemplo #2 bindec() interpreta a entrada como inteiros sem sinal

<?php
/*
* A lição deste exemplo está na saída
* e não no código do PHP em si.
*/

$magnitude_lower = pow(2, (PHP_INT_SIZE * 8) - 2);
p($magnitude_lower - 1);
p($magnitude_lower, 'Percebeu a rolagem? Veja da próxima vez...');

p(PHP_INT_MAX, 'PHP_INT_MAX');
p(~PHP_INT_MAX, 'interpretado como um a mais que PHP_INT_MAX');

if (
PHP_INT_SIZE == 4) {
$note = 'interpretado como o maior inteiro sem sinal';
} else {
$note = 'interpretado como o maior inteiro sem sinal
(18446744073709551615) porém distorcido pela precisão de float'
;
}
p(-1, $note);


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

$format = '%0' . (PHP_INT_SIZE * 8) . 'b';
$bin = sprintf($format, $input);
echo
"binário: $bin\n";

ini_set('precision', 20); // Para legibilidade em máquinas 64 bits.
$dec = bindec($bin);
echo
'bindec(): ' . $dec . "\n";

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

echo
"\n";
}
?>

Saída do exemplo acima em máquinas de 32 bits:

input:        1073741823
binary:       00111111111111111111111111111111
bindec():     1073741823

input:        1073741824
binary:       01000000000000000000000000000000
bindec():     1073741824
NOTE:         Percebeu a rolagem?  Veja da próxima vez...

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

input:        -2147483648
binary:       10000000000000000000000000000000
bindec():     2147483648
NOTE:         interpretado como um a mais que PHP_INT_MAX

input:        -1
binary:       11111111111111111111111111111111
bindec():     4294967295
NOTE:         interpretado como o maior inteiro sem sinal

Saída do exemplo acima em máquinas de 64 bits:

input:        4611686018427387903
binary:       0011111111111111111111111111111111111111111111111111111111111111
bindec():     4611686018427387903

input:        4611686018427387904
binary:       0100000000000000000000000000000000000000000000000000000000000000
bindec():     4611686018427387904
NOTE:         Percebeu a rolagem?  Veja da próxima vez...

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

input:        -9223372036854775808
binary:       1000000000000000000000000000000000000000000000000000000000000000
bindec():     9223372036854775808
NOTE:         interpretado como um a mais que PHP_INT_MAX

input:        -1
binary:       1111111111111111111111111111111111111111111111111111111111111111
bindec():     18446744073709551616
NOTE:         interpretado como o maior inteiro sem sinal
              (18446744073709551615) porém distorcido pela precisão de float

Notas

Nota:

A função pode converter números que são grandes demais para caber no tipo int da plataforma, valores maiores são retornados como float neste caso.

Veja Também

add a note add a note

User Contributed Notes 10 notes

up
5
info at rickdg dot nl
13 years ago
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;
    }
}
?>
up
3
gwbdome at freenet dot de
19 years ago
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));
}
up
2
martin at punix dot de
20 years ago
## 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)
up
1
Nitrogen
14 years ago
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.
up
1
alan hogan dot com slash contact
16 years ago
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);
}
?>
up
1
patrick dot boens at latosensu dot be
11 years ago
Left-shift a string by a number of bytes
<?php
function STR_shl( $szStr,$nBits )
/*-----------------------------*/
{
    if (
$nBits < 1 || $nBits > 7 )                                     /* If not adequate number of bits */
   
{
        return (
$szStr );                                              /* Return the original string */
   
}   /* if ( $nBits < 1 || $nBits > 7 ) */

   
if ( ( $iLength = strlen( $szStr ) ) <= 0 )                         /* If string empty */
   
{
        return (
$szStr );                                              /* Return the original string */
   
}   /* if ( ( $iLength = strlen( $szStr ) ) <= 0 ) */

   
$szRetVal   = '';                                                   /* Create an empty string */

   
$szBits     = STR_Binary( $szStr );                                 /* $szStr in bits */
   
$szLostBits = STR_Left( $szBits,$nBits );                           /* The $nBits leftmost bits of the string */
   
$szShifted  = substr( $szBits,$nBits ) . $szLostBits;               /* $szStr left shifted */

   
for ( $i = 0;$i < $iLength;$i++ )                                   /* Treat the entire string (per slice of 8 bits) */
   
{
       
$szRetVal .= chr( bindec( substr( $szShifted,$i * 8,8 ) ) );    /* Concatenate the CHR to the result string */
   
}   /* for ( $i = 0;$i < $iLength;$i++ ) */

   
return ( $szRetVal );                                               /* Return result to caller */
}
?>

Right-shift a string by a number of bytes
<?php

function STR_shr( $szStr,$nBits )
/*-----------------------------*/
{
    if (
$nBits < 1 || $nBits > 7 )                                     /* If not adequate number of bits */
   
{
        return (
$szStr );                                              /* Return the original string */
   
}   /* if ( $nBits < 1 || $nBits > 7 ) */

   
if ( ( $iLength = strlen( $szStr ) ) <= 0 )                         /* If string empty */
   
{
        return (
$szStr );                                              /* Return the original string */
   
}   /* if ( ( $iLength = strlen( $szStr ) ) <= 0 ) */

   
$szRetVal   = '';                                                   /* Create an empty string */

   
$szBits     = STR_Binary( $szStr );                                 /* $szStr in bits */
   
$szLostBits = STR_Right( $szBits,$nBits );                          /* The $nBits rightmost bits of the string */
   
$szShifted  = $szLostBits . substr( $szBits,0,-$nBits );            /* $szStr right shifted */

   
for ( $i = 0;$i < $iLength;$i++ )                                   /* Treat the entire string (per slice of 8 bits) */
   
{
       
$szRetVal .= chr( bindec( substr( $szShifted,$i * 8,8 ) ) );    /* Concatenate the CHR to the result string */
   
}   /* for ( $i = 0;$i < $iLength;$i++ ) */

   
return ( $szRetVal );                                               /* Return result to caller */
}
?>

Additional functions used by the two preceding:
<?php
function STR_Binary( $szStr )
/*-------------------------*/
{
   
$szRetVal = '';                                                     /* Ready to return an empty string */

   
if ( ( $iLength = strlen( $szStr ) ) > 0 )                          /* If string NOT empty */
   
{
        for (
$i = 0; $i < $iLength;$i++ )                              /* Treat each character of the string */
       
{
           
$szRetVal .= sprintf( '%08b',ord( $szStr[$i] ) );           /* Turn this char to a binary representation (8 bits) */
       
}   /* for ( $i = 0; $i < $iLength;$i++ ) */
   
}   /* if ( ( $iLength = strlen( $szStr ) ) > 0 ) */

   
return ( $szRetVal );                                               /* Return result to caller */
}

function
STR_Left( $szStr,$iCount = 1 )
/*----------------------------------*/
{
    return
substr( $szStr,0,$iCount );
}  
/* End of function strleft() */

function STR_Right( $szString,$iCount )
/*----------------------------------*/
{
    return
substr( $szString,0 + strlen( $szString ) - $iCount,$iCount );
}
?>
up
0
mashematician at gmail dot com
16 years ago
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');

?>
up
-2
jpfstange at gmail dot com
8 years ago
<?php

      
//binfloat (For single precision floating point numbers)
       //IEE754
       //https://en.wikipedia.org/wiki/Single-precision_floating-point_format

       
function binfloat(Array $num){

               
$sign           =       $num[0] ? 1 : -1;                       //1 bit
               
$exponent       =       pow(2,bindec(implode('',array_slice($num,1,8)))-127);
               
$fraction       =       array_slice($num,9,count($num));        //23 bits
               
$fracSum        =       1;

                for(
$i=0;$i<23;$i++){

                       
$fracSum += $fraction[$i] * pow(2,-1-$i);

                }

                return
$fracSum*$exponent;

        }

       
$num    =       isset($_GET['num']) ? $_GET['num'] : '00111110001000000000000000000000';

        if(
strlen($num)<32){

                echo
"Invalid binary number $num\n";
                exit(
1);

        }

       
$num    =       str_split($num);

        echo
sprintf('Num is: [%s]%s',implode('',$num),"\n");
        echo
sprintf('Result is: %s%s',binfloat($num),"\n");
up
-2
flashpack at gmail dot com
15 years ago
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 ;
}
?>
up
-1
nodarinodo at mail dot ru
15 years ago
<?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;
    }
?>
To Top