decbin

(PHP 4, PHP 5)

decbinПереводит число из десятичной системы счисления в двоичную

Описание

string decbin ( int $number )

Возвращает строку, содержащую двоичное представление указанного аргумента number.

Список параметров

number

Десятичное число для преобразования

Область ввода для 32-битных машин
положительный number отрицательный number возвращаемое значение
0   0
1   1
2   10
... и так далее ...
2147483646   1111111111111111111111111111110
2147483647 (наибольший знаковый integer)   1111111111111111111111111111111 (31 единичка)
2147483648 -2147483648 10000000000000000000000000000000
... и так далее ...
4294967294 -2 11111111111111111111111111111110
4294967295 (наибольший беззнаковый integer) -1 11111111111111111111111111111111 (32 единички)
Область ввода для 64-битных машин
положительный number отрицательный number возвращаемое значение
0   0
1   1
2   10
... и так далее ...
9223372036854775806   111111111111111111111111111111111111111111111111111111111111110
9223372036854775807 (наибольший знаковый integer)   111111111111111111111111111111111111111111111111111111111111111 (63 единички)
  -9223372036854775808 1000000000000000000000000000000000000000000000000000000000000000
... и так далее ...
  -2 1111111111111111111111111111111111111111111111111111111111111110
  -1 1111111111111111111111111111111111111111111111111111111111111111 (64 единички)

Возвращаемые значения

Бинарное строковое представление number

Примеры

Пример #1 Пример использования decbin()

<?php
echo decbin(12) . "\n";
echo 
decbin(26);
?>

Результат выполнения данного примера:

1100
11010

Смотрите также

  • bindec() - Двоичное в десятичное
  • decoct() - Переводит число из десятичной системы счисления в восьмеричную
  • dechex() - Переводит число из десятичной системы счисления в шестнадцатиричную
  • base_convert() - Преобразование числа между произвольными системами счисления
  • printf() - Выводит отформатированную строку, используя форматы %b, %032b или %064b
  • sprintf(), используя форматы %b, %032b или %064b

Коментарии

Автор:
HERE you can convert 64bit instead of 32bit with the standard decbin
<?
function bigdecbin($dec,$doublewords=1) {
   
$erg "";
    do {
         
$rest $dec%2147483648;
          if (
$rest<0$rest+=2147483648;
         
$erg str_pad(decbin($rest),31,"0",STR_PAD_LEFT).$erg;
         
$dec = ($dec-$rest)/2147483648;
      } while ((
$dec>0)&&(!($dec<1)));
     
      return 
str_pad($erg,$doublewords*31,"0",STR_PAD_LEFT);
}

echo 
"<pre>";
for (
$i=1.5*2147483647.0-10;$i<1.5*2147483647.0+10;$i++) {
    echo 
"DEC:".$i." BIN:".bigdecbin($i,2)."<br>";
}
echo 
"</pre>";
?>
2001-10-08 16:47:21
http://php5.kiev.ua/manual/ru/function.decbin.html
Another larger-than-31-bit function.
Works for very large numbers, but at the expense of perfect bit-precision as the size increases (I noticed rounding errors past 16 or so decimal places) so use with caution, and only when decbin() won't cut it.

function Dec2Bin($number) {
    while ($number >= 256) {
        $bytes[] = (($number / 256) - (floor($number / 256))) * 256;
        $number = floor($number / 256);
    }
    $bytes[] = $number;
    for ($i=0;$i<count($bytes);$i++) {
        $binstring = (($i == count($bytes) - 1) ? decbin($bytes[$i]) : str_pad(decbin($bytes[$i]), 8, "0", STR_PAD_LEFT)).$binstring;
    }
    return $binstring;
}
2002-02-28 21:15:16
http://php5.kiev.ua/manual/ru/function.decbin.html
Автор:
base_convert( base_convert('100001000100000000010001001000
0100100000001111111111111111111',2,10),10,2);

return
'1000010001000000000100010010000
100100000010000000000000000000'

this function doesn't work
2005-02-08 09:27:16
http://php5.kiev.ua/manual/ru/function.decbin.html
Автор:
Just an example:
If you convert 26 to bin you'll get 11010, which is 5 chars long. If you need the full 8-bit value use this:

$bin = decbin(26);
$bin = substr("00000000",0,8 - strlen($bin)) . $bin;

This will convert 11010 to 00011010.
2006-01-06 08:29:08
http://php5.kiev.ua/manual/ru/function.decbin.html
Автор:
A fast function to convert a binary string to a bit sequence

<?php

function BinString2BitSequence($mystring) {   
   
$mybitseq "";
   
$end strlen($mystring);
    for(
$i $i $end$i++){
       
$mybyte decbin(ord($mystring[$i])); // convert char to bit string
       
$mybitseq .= substr("00000000",0,strlen($mybyte)) . $mybyte// 8 bit packed
   
}
    return 
$mybitseq;
}

echo 
BinString2BitSequence("ABCDEF"); // OUTPUT=010000010100001001000011010001000100010101000110

?>
2006-02-04 04:57:38
http://php5.kiev.ua/manual/ru/function.decbin.html
<?php
Print bindecValues("1023");

function 
bindecValues($decimal$reverse=false$inverse=false) {
/*
1. This function takes a decimal, converts it to binary and returns the
     decimal values of each individual binary value (a 1) in the binary string.
     You can use larger decimal values if you pass them to the function as a string!
2. The second optional parameter reverses the output.
3. The third optional parameter inverses the binary string, eg 101 becomes 010.
-- darkshad3 at yahoo dot com
*/

   
$bin decbin($decimal);
    if (
$inverse) {
       
$bin str_replace("0""x"$bin);
       
$bin str_replace("1""0"$bin);
       
$bin str_replace("x""1"$bin);
    }
   
$total strlen($bin);
   
   
$stock = array();
   
    for (
$i 0$i $total$i++) {
        if (
$bin{$i} != 0) {
           
$bin_2 str_pad($bin{$i}, $total $i0);
           
array_push($stockbindec($bin_2));
        }
    }
   
   
$reverse rsort($stock):sort($stock);
    return 
implode(", "$stock);
}
?>

The printed result is : 1, 2, 4, 8, 16, 32, 64, 128, 256, 512
2007-02-15 17:15:19
http://php5.kiev.ua/manual/ru/function.decbin.html
Careful trying binary-wise tests with integers:

# FFFFFFFF
command: php -r 'print(decbin(4294967295)."\n");'
result: 11111111111111111111111111111111

# C3E9CAC8
command: php -r 'print(decbin(3286878920)."\n");'
result: 11000011111010011100101011001000

# regardless of specifying "(int)", using bitwise AND:
command: php -r 'print((int)(3286878920 & 4294967295)."\n");'
result: -1008088376 (int)

# now the expected result will happen (guess the performance impact)
command: php -r 'print(bindec(decbin((3286878920 & 4294967295)))."\n");'
result: 3286878920 (float)

additional note: if you "bitwise and" some random bits with a sequence of 1-bit of the same length, the expected result is the same "random bits sequence" unchanged. If you want to keep this in the integer world for faster comparisons, you risk messing your result for the signed integer size limitation. The maximum value you can use for the desired result is (7FFFFFFF -- or integer 2147483647), half of the maximum 'unsigned' integer 32-bit(platform-dependent) value.
2008-08-24 09:25:15
http://php5.kiev.ua/manual/ru/function.decbin.html
Автор:
I think this is the best function. Is almost endlessy (till 2^50 or something)

<?php
function bin($int)
{
   
$i 0;
   
$binair "";
    while(
$int >= pow(2,$i))
    {
       
$i++;
    }
   
    if(
$i != 0)
    {
       
$i $i-1//max i
   
}

    while(
$i >= 0)
    {
        if(
$int pow(2,$i) < 0)
        {
           
$binair "0".$binair;
        }else{
           
$binair "1".$binair;
           
$int $int pow(2,$i);
        }
       
       
$i--;
    }
    return 
$binair;
}

$getal $_GET['getal'];

   
echo 
bin($getal);
?>
2008-10-04 08:04:51
http://php5.kiev.ua/manual/ru/function.decbin.html
Автор:
Decimal to Binary conversion using the BCMath extension.

<?php

function BCDec2Bin($Input='') {
 
$Output='';
 if(
preg_match("/^\d+$/",$Input)) {
   while(
$Input!='0') {
     
$Output.=chr(48+($Input{strlen($Input)-1}%2));
     
$Input=BCDiv($Input,'2');
   }
   
$Output=strrev($Output);
 }
 return((
$Output!='')?$Output:'0');
}

?>

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

See also: my 'BCBin2Dec' function on the 'bindec' document.
Enjoy,
Nitrogen.
2009-07-21 13:30:59
http://php5.kiev.ua/manual/ru/function.decbin.html
Автор:
This is my System:

You can convert a decimal number to a number system you want, like the binary system.

<?php
   
   
function Dec2oSys($numberDec$SysNum)
    {
        if(
$numberDec != 0)
        {
           
$numberOSys "";
            for (; 
$numberDec 0;) {
               
$numberDecBefore $numberDec;
               
$numberDec $numberDec $SysNum;
               
$pos strpos($numberDec'.');
                if(
$pos != false)
                {
                   
$numberDec floor($numberDec);
                   
$numberOSys .= $numberDecBefore floor($numberDec) * $SysNum;
                   
$rest $numberDecBefore floor($numberDec) * $SysNum;
                }
                else
                {
                   
$numberOSys .= "0";
                   
$rest 0;
                   
                }
                print 
$numberDec."; Rest:".$rest."<br/>";
            }
        }
        else
        {
           
$numberOSys "0";
        }
        return 
strrev($numberOSys);
    }
   
    print 
Dec2oSys(1002);
   
?>
2013-03-05 20:00:08
http://php5.kiev.ua/manual/ru/function.decbin.html
A little useful little function that returns a binary string with leading 0s:

function d2b($n) {
  return str_pad(decbin($n), 16, "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
2013-08-23 18:09:31
http://php5.kiev.ua/manual/ru/function.decbin.html
hi folks, i struggled for a day to get a big decimal number converted into binary, on the windows platform.
finally with bcmath functions this is what worked for me.

function bc_convert2bin($string) {

    //got it to work with bcmath functions, works for 64 bit on 32 bit windows machine
    $finished=0;
    $base=2;
    $bin_nr='';

    if(preg_match("/[^0-9]/", $string)) {
        for($i=0; $string!=chr($i); $i++) {
            $dec_nr=$i;
        }
    } else {
        $dec_nr=$string;
    }
    //while( $dec_nr>$base ) {
    while( bccomp($dec_nr,$base) == 1 ) {

        //$base=$base*2;
        $base=bcmul($base,'2');
        //if($base>$dec_nr) {
        if( bccomp($base,$dec_nr) == 1 ) {
            //$base=$base/2;
            $base=bcdiv($base,'2');
            break;
        }
    }

    while(!$finished) {

        //if(($dec_nr-$base)>0) {
        if( bccomp( bcsub($dec_nr,$base) , 0) == 1 ) {

            //$dec_nr=$dec_nr-$base;
            $dec_nr=bcsub($dec_nr,$base);
            $bin_nr.=1;
            //$base=$base/2;
            $base=bcdiv($base,'2');

        //} elseif(($dec_nr-$base)<0) {
        } elseif( bccomp( bcsub($dec_nr,$base) , 0) == -1 ) {

            $bin_nr.=0;
            //$base=$base/2;
            $base=bcdiv($base,'2');

        //} elseif(($dec_nr-$base)==0) {
        } elseif( bccomp( bcsub($dec_nr,$base) , 0) == 0 ) {

            $bin_nr.=1;
            $finished=1;
            //while($base>1) {
            while( bccomp($base,1) == 1 ) {

                $bin_nr.=0;
                //$base=$base/2;
                $base=bcdiv($base,'2');

            }
        }
    }
    return $bin_nr;
}
2014-01-22 11:06:59
http://php5.kiev.ua/manual/ru/function.decbin.html
Автор:
To add leading zeros I prefer the following:
<?php
// Add leading zeros
$bin sprintf"%08d"decbin26 )); // "00011010"
?>
2014-02-12 00:07:36
http://php5.kiev.ua/manual/ru/function.decbin.html
If you want leading zeros use php built-in features instead of custom functions

<?php
printf
('%08b'$decimal);
?>

>> printf('%08b', E_NOTICE)
>> 00001000
2015-07-08 20:29:32
http://php5.kiev.ua/manual/ru/function.decbin.html
Print as binary format with leading zeros into a variable in one simple statement.

<?php
    $binary 
sprintf('%08b'$decimal);    // $decimal = 5;
   
echo $binary;    // $binary = "00000101";
?>
2017-01-05 03:08:07
http://php5.kiev.ua/manual/ru/function.decbin.html
Автор:
The GNU MP library (book.gmp) provides methods to efficiently convert binary strings of any length to their binary representation (i.e., a `decbin` equivalent for strings).

<?php

$str 
random_bytes(1024); // binary string example

$result gmp_strval(gmp_import($str), 2); // see manual for options such as endianness

$zeroPadded sprintf('%0' . (strlen($str) * 8) . 's'$result); // zero-pad if needed, e.g. with str_pad, or sprintf as shown here

$strAgain gmp_export(gmp_init($result2)); // reverse operation similar to bindec

?>
2017-02-02 05:42:15
http://php5.kiev.ua/manual/ru/function.decbin.html
Автор:
Regarding trailing zeros, after test all the option mention here by others, i have performed my own tests regarding efficiency, here are the results:

<?php

$decimal 
9;

$time_start microtime(true);
for (
$i=0;$i<1000;$i++){
$bin printf('%08b'$decimal);
}
$time_end microtime(true);
$time $time_end $time_start;
echo 
"<hr>Duracion $time segundos<br>\n";
echo 
$bin '<br>';

$time_start microtime(true);
for (
$i=0;$i<1000;$i++){
$bin sprintf"%08d"decbin$decimal ));
}
$time_end microtime(true);
$time $time_end $time_start;
echo 
"<hr>Duracion $time segundos<br>\n";
echo 
$bin '<br>';

$time_start microtime(true);
for (
$i=0;$i<1000;$i++){
$bin decbin($decimal);
$bin substr("00000000",0,strlen($bin)) . $bin;
}
$time_end microtime(true);
$time $time_end $time_start;
echo 
"<hr>Duracion $time segundos<br>\n";
echo 
$bin '<br>';

?>

results

0000100100001001000010010000100.... (output is echoed 1000 times)
Duracion 0.0134768486023 segundos
8
Duracion 0.00054407119751 segundos
00001001
Duracion 0.000833988189697 segundos
00001001

Thus the winner is 
<?php
$bin 
sprintf"%08d"decbin$decimal ));
?>
2017-03-03 09:09:44
http://php5.kiev.ua/manual/ru/function.decbin.html

    Поддержать сайт на родительском проекте КГБ