decbin
(PHP 4, PHP 5)
decbin — Decimal to binary
Описание
string decbin
( int $number
)
Returns a string containing a binary representation of the given number argument. The largest number that can be converted is 4294967295 in decimal resulting to a string of 32 1's.
Список параметров
- number
-
Decimal value to convert
Возвращаемые значения
Binary string representation of number
Примеры
Пример #1 decbin() example
<?php
echo decbin(12) . "\n";
echo decbin(26);
?>
Результат выполнения данного примера:
1100 11010
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Математические расширения
- Математические функции
- 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
- intdiv
- 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
Коментарии
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;
}
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.
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
?>
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;
}
To add leading zeros I prefer the following:
<?php
// Add leading zeros
$bin = sprintf( "%08d", decbin( 26 )); // "00011010"
?>
If you want leading zeros use php built-in features instead of custom functions
<?php
printf('%08b', $decimal);
?>
>> printf('%08b', E_NOTICE)
>> 00001000
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";
?>
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($result, 2)); // reverse operation similar to bindec
?>
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,8 - 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 ));
?>