(PHP 4, PHP 5)
decbin — 十进制转换为二进制
$number
)
返回一字符串,包含有给定
number
参数的二进制表示。所能转换的最大数值为十进制的
4294967295,其结果为 32 个 1 的字符串。
number
Decimal value to convert
positive number |
negative number |
return value |
---|---|---|
0 | 0 | |
1 | 1 | |
2 | 10 | |
... normal progression ... | ||
2147483646 | 1111111111111111111111111111110 | |
2147483647 (largest signed integer) | 1111111111111111111111111111111 (31 1's) | |
2147483648 | -2147483648 | 10000000000000000000000000000000 |
... normal progression ... | ||
4294967294 | -2 | 11111111111111111111111111111110 |
4294967295 (largest unsigned integer) | -1 | 11111111111111111111111111111111 (32 1's) |
positive number |
negative number |
return value |
---|---|---|
0 | 0 | |
1 | 1 | |
2 | 10 | |
... normal progression ... | ||
9223372036854775806 | 111111111111111111111111111111111111111111111111111111111111110 | |
9223372036854775807 (largest signed integer) | 111111111111111111111111111111111111111111111111111111111111111 (63 1's) | |
-9223372036854775808 | 1000000000000000000000000000000000000000000000000000000000000000 | |
... normal progression ... | ||
-2 | 1111111111111111111111111111111111111111111111111111111111111110 | |
-1 | 1111111111111111111111111111111111111111111111111111111111111111 (64 1's) |
Binary string representation of number
Example #1 decbin() 例子
<?php
echo decbin(12) . "\n";
echo decbin(26);
?>
以上例程会输出:
1100 11010
Silas R (15) (2013-03-05 18:00:08)
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(100, 2);
?>
p2233 at hotmail dot com (2011-06-08 04:22:20)
Here's a generic binary output formatter. It is based on the function in above comments, but lets you specify how many bits your want formatted.
<?php
/**
* Output an x bit string representing a binary value.
* Default is 8 bits ie. 0000 0000
* eg. fmt_binary($x,32) : output a 32-bit binary representation of $x
* @param string $x x-bit formatted binary
*/
function fmt_binary($x, $numbits = 8) {
// Convert to binary
$bin = decbin($x);
$bin = substr(str_repeat(0,$numbits),0,$numbits - strlen($bin)) . $bin;
// Split into x 4-bits long
$rtnval = '';
for ($x = 0; $x < $numbits/4; $x++) {
$rtnval .= ' ' . substr($bin,$x*4,4);
}
// Get rid of first space.
return ltrim($rtnval);
}
?>
okram at NOSPAMcivokram dot com (2011-01-06 19:04:30)
Here's a simple decbin function that uses BC Math. It works only for positive numbers and has no upper limit for $dec (except computation time).
<?php
function bcdecbin($dec) {
$bin = '';
while ($dec) {
$m = bcmod($dec, 2);
$dec = bcdiv($dec, 2);
$bin .= abs($m);
}
return strrev($bin);
}
?>
J.M. van Leeuwen (2010-08-23 01:11:50)
I was surprised by decbin's size limitation. Here is a function without size limitation. It supports much bigger values (like 11.435.168.214), but doesn't support signs because I didn't need signs (yet).
<?php
function dec2bin($dec){
// Better function for dec to bin. Support much bigger values, but doesn’t support signs
for($b='',$r=$dec;$r>1;){
$n = floor($r/2); $b = ($r-$n*2).$b; $r = $n; // $r%2 is inaccurate when using bigger values (like 11.435.168.214)!
}
return ($r%2).$b;
}
?>
Nitrogen (2009-07-21 10:30:59)
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.
Kay (2008-10-04 05:04:51)
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);
?>
avenger at avenger dot ws (2008-08-24 06:25:15)
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.
darkshad3 at yahoo dot com (2007-02-15 15:15:19)
<?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
heavyraptor (2006-07-27 08:18:21)
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
Xavier Daull (2006-02-04 02:57:38)
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
?>
(2006-01-06 06:29:08)
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 at gmail dot com (2006-01-03 05:00:01)
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.
Stefan (2005-03-02 23:35:04)
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!
(2005-02-08 07:27:16)
base_convert( base_convert('100001000100000000010001001000
0100100000001111111111111111111',2,10),10,2);
return
'1000010001000000000100010010000
100100000010000000000000000000'
this function doesn't work
(2004-11-27 07:26:42)
<?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
?>
gene_wood at example dot com (2003-10-15 02:38:40)
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;
}
php at silisoftware dot com (2002-02-28 19:15:16)
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;
}
ajl at gmx dot de (2001-10-08 13:47:21)
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>";
?>