Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Mathematical Functions : decbin

decbin

Decimal to binary (PHP 4, PHP 5)
string decbin ( int number )

Example 1142. decbin() example

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

The above example will output:

1100
11010

Related Examples ( Source code ) » decbin



Code Examples / Notes » decbin

gthompsn

To pad leading zeroes onto the output of decbin, I prefer to use something like this for my 8-bit integer:
$qcStr=sprintf("%08d",decbin($myInt));
--Greg T.


gene_wood

This is just an extension off of the first comment. This is a pair of function to convert from an array of binary values to an integer and vice versa. It has a touch of error checking.
/**
* Will convert an array of binary values into an integer for storage
*
* @param        array       $data_array     Array of 31 or less binary values
* @return       integer                     Encoded integer
*/
function array_to_binary_int($data_array) {
   if (count($data_array) > 31) return FALSE;
   foreach ($data_array as $key => $value) {
       if ($value) $data_array[$key] = 1;
       if (!$value) $data_array[$key] = 0;
   }
   $binstring = strrev(implode('', $data_array));
   $bit_integer = bindec($binstring);
   return $bit_integer;
}
/**
* Will convert a stored integer into an array of binary values
*
* @param        integer       $data_integer     Encoded integer
* @return       integer                         Array of binary values
*/
function binary_int_to_array($data_integer) {
   if (($data_integer > 2147483647) OR ($data_integer < 0)) return FALSE;
   $binstring = strrev(str_pad(decbin ($data_integer),31,"0",STR_PAD_LEFT));
   $bitarray = explode(":",chunk_split($binstring, 1, ":"));
   return $bitarray;
}


sam

or pad the string like:
  substr("000" . $decbin($i), -3, 3);


dcramer

matt at nexxmedia dot com (06-Dec-2002 04:29) said:
<?php
...
strrev(str_pad(decbin($decval),8,"0",STR_PAD_LEFT));
...
?>
<?php
str_pad(decbin ($decval),8,'0');
?>
produces the same results!
--
That's incorrect, it does not produce the same results.


stefan

matt at nexxmedia dot com (06-Dec-2002 04:29) said:
<?php
...
strrev(str_pad(decbin($decval),8,"0",STR_PAD_LEFT));
...
?>
<?php
str_pad(decbin ($decval),8,'0');
?>
produces the same results!


06-jan-2006 02:29

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.


j dot preece

It occured to me there must be a simple way to produce binary numbers from decimal ones with any number of bits, here's my attempt at a decimal to extended binary function. I hope the comments make it clear:
<?php
function decextbin($decimalnumber,$bit)
{
/* decextbin function
by James Preece (j.preece@gmail.com)
http://www.lovingit.co.uk

Please feel free to use this function. If you find
if useful I would love to hear from you.
*/
/* Function to return a binary number with as many
bits as are requested...

This works on the following principal. A binary number
represents a figure 2,4,8,16 etc. If we work from the
top down we can determine if a number contains each figure
as a fraction and then work with what remains.

For example, if we wish to display the number 10 as a 4 bit
number we first discover the figure of the maximum bit by doubling
four times:
1 2 4 8

The maxiumum figure is 8.

Next we work down the figures:

8 goes in to 10 so the first digit is 1 leaving 2
4 does not go in to 2 so the second digit is 0
2 goes in to 2 so the third digit is 1
1 does not go in to 0 so the fourth digit is 0

Output: 1010

Now for the actual code!
First we find that maximum value represented by the
leftmost binary digit. For error checking purposes
we also calulate the maximum number we can display
using the number of bits requested: */

$maxval = 1;
$sumval = 1;
for($i=1;$i<$bit;$i++)
{
$maxval = $maxval * 2;
$sumval = $sumval + $maxval;
}

/* Using our sumval we now check if it is possible
to display the decimal number our function received: */

if ($sumval < $decimalnumber) return 'ERROR - Not enough bits to display this figure in binary.';

/* Then we work down through the figures, to get a
better idea of how this works remove the commenting
from the echo lines */

for($bitvalue=$maxval;$bitvalue>=1;$bitvalue=$bitvalue/2)
{
//echo 'Bit Value: '.$bitvalue.'<br />';
//echo 'Decimal Number: '.$decimalnumber.'<br />';

if (($decimalnumber/$bitvalue) >= 1) $thisbit = 1; else $thisbit = 0;

//echo 'This Bit: '.$thisbit.'<br /><br />';

if ($thisbit == 1) $decimalnumber = $decimalnumber - $bitvalue;

$binarynumber .= $thisbit;
}
/* Finally we return the output... */
return $binarynumber;
}
?>
An example usage might be like so:
<?php
for ($i = 0;$i<=8;$i++)
{
echo decextbin($i,4).'<br />';
}
?>
Output:
0000
0001
0010
0011
0100
0101
0110
0111
1000
No need for padding or anything - also goes way over 32 bits. Huzzah. I suspect its limited by the maximum string length in php. Hmmm - Not sure what that is.


heavyraptor

I wrote the decoder for the output of Xavier Daull's function "BinString2BinSequence".
<?php
function bs2string($bitseq) {
 if (strlen($bitseq) % 8 != 0) return false;
 $str = "";
 $bitseqlen = strlen($bitseq);
 for($i = 0; $i < $bitseqlen; $i += 8) {
  $str .= chr(bindec(substr($bitseq,$i,8)));
 }
 return $str;
}
?>
Have fun


sam yong - hellclanner

I was trying out and learning about bits when i made one of the function worked as expected. The function i just made is a clone of decbin(); but it is not as good as the native one. Just a simple idea of how decbin works.
For numbers, you need to specify the (int) type before using because the result might be different if you leave it out. Great value of float specified will result in an overflow so the max number is returned(0xFFFFFFFF).
The Return is a string with binary in it. I have managed to fix the 32th resource bit loss by reading up on other codes written by others' notes on php.net
<?php
function mydecbin($a = 0){
if(is_int($a)){$a = (float)$a;}
$a = (float)((float)$a>=0?(float)$a:(float)$a*-1);
if($a >= 0xFFFFFFFF){return (string)"11111111111111111111111111111111";}
$buff =array();
$res = ($a & 0x7FFFFFFF) >> 32;
if(0x80000000 & $a){ $res |= (1<<(31-32)); }
$a = floor($a / 2);
while(ceil($a / 2) > 0){
if(ceil($a%2) > -1){$buff[] = ceil($a%2);}
$a = floor($a / 2);}
$buff = array_reverse($buff); $r = '';
foreach($buff as $b){$r .= $b;}
$r .= floor(($res>0?$res:$res*-1)%2);
return (string)$r;
}
// Usage:
$n = (int)281474976711000;
echo "\n\n";
var_dump(mydecbin($n)); // var dump the returned value
echo ' vs '."\n";
var_dump(decbin($n)); // do a check
echo "\n";
var_dump(mydecbin($n) === decbin($n)); // value and type check
/*
Outputs:
string(9) "101011000"
 vs
string(9) "101011000"
bool(true)
*/
?>
Cheers
Sam Yong


sterba

I had the same problem on PHP 3.0.9, so the str_repeat was not an option. This maight help:
while (strlen($result)<3) $result="0".$result;


oubiwann

Here's a little binary for counting on your fingers up to 1023 (from 0). It formats/pads the binary number like you wanted.
<pre>
&lt;?php
print "<pre>Dec  : Finger Positions\n";
print "---- : ----------------\n";
for ( $i=0; strlen($bin) <=10; ++$i ) {
  $bin = decbin($i);
  $output = sprintf("%04d : ", $i);
  $bin_temp = $bin;
  while ( strlen($bin_temp) < 10 ) {
     $bin_temp = "0" . $bin_temp;
  }
  print $output . $bin_temp . "\n";
}
print "</pre>\n";
?>
</pre>
I tried using sprintf("%04d : %10d", $i, $bin) and sprintf("%04d : %10d", $i, $bin + 0), the later an attempt to force the string to act as a number, but neither worked. Maybe it was me...


ajl

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)."
";
}
echo "</pre>";
?>


nospam dot me

do this to pad the binary:
str_pad(decbin($dec),3,"0",STR_PAD_LEFT);
output like:
001
010


08-feb-2005 03:27

base_convert( base_convert('100001000100000000010001001000
0100100000001111111111111111111',2,10),10,2);
return
'1000010001000000000100010010000
100100000010000000000000000000'
this function doesn't work


php

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


matt

A quick one-line bitmask. Great for storing a list of checkbox settings in a MySQL database. This one works for TinyINT (8 bits). Note: I had to make it two lines here so it would fit.
$decval = 83;
/*
decimal to binary, padded with 0s, reversed so the least significant digit is first, split with colons, and then separated into an array
*/
$binstring = strrev(str_pad(decbin ($decval),8,"0",STR_PAD_LEFT))
$bitarray = explode(":",chunk_split($binstring, 1, ":"));
for($x = 0; $x < 8; $x++) {
echo $bitarray[$x]." ";
}
// will output 1 1 0 0 1 0 1 0


xavier daull

A fast function to convert a binary string to a bit sequence
<?php
function BinString2BitSequence($mystring) {    
$mybitseq = "";
$end = strlen($mystring);
for($i = 0 ; $i < $end; $i++){
$mybyte = decbin(ord($mystring[$i])); // convert char to bit string
$mybitseq .= substr("00000000",0,8 - strlen($mybyte)) . $mybyte; // 8 bit packed
}
return $mybitseq;
}
echo BinString2BitSequence("ABCDEF"); // OUTPUT=010000010100001001000011010001000100010101000110
?>


darkshad3

<?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 - $i, 0);
array_push($stock, bindec($bin_2));
}
}

$reverse ? rsort($stock):sort($stock);
return implode(", ", $stock);
}
?>
The printed result is : 1, 2, 4, 8, 16, 32, 64, 128, 256, 512


27-nov-2004 03:26

<?php // function for converting values >= 2147483648 (2^16)
 function decbin4long($long) {
   return base_convert($long,10,2);
 } // idea from http://phpclub.ru/talk/showthread.php?postid=407488
?>


Change Language


Follow Navioo On Twitter
abs
acos
acosh
asin
asinh
atan2
atan
atanh
base_convert
bindec
ceil
cos
cosh
decbin
dechex
decoct
deg2rad
exp
expm1
floor
fmod
getrandmax
hexdec
hypot
is_finite
is_infinite
is_nan
lcg_value
log10
log1p
log
max
min
mt_getrandmax
mt_rand
mt_srand
octdec
pi
pow
rad2deg
rand
round
sin
sinh
sqrt
srand
tan
tanh
eXTReMe Tracker