问题
I'm trying to make decimal to binary convertor without using decbin() function. I tried smth like this (which is ok but it needs to be reversed):
$dec=101;
while ($dec>=1){
$bin = $dec % 2;
$dec = round($dec/2, 0, PHP_ROUND_HALF_DOWN);
print "$bin";
}// output:1010011
How could I reverse the output to 1100101? Thanks in forward. :)
回答1:
To convert a decimal integer to binary, repeatedly divide it by 2 — using integer division — until it becomes 0. The remainders at each step, which are 0s and 1s, represent the binary number, when strung together in the reverse order in which they were generated.
<?php
function dec2bin_i($decimal_i)
{
bcscale(0);
$binary_i = '';
do
{
$binary_i = bcmod($decimal_i,'2') . $binary_i;
$decimal_i = bcdiv($decimal_i,'2');
} while (bccomp($decimal_i,'0'));
return($binary_i);
}
?>
Test case
<?php
echo dec2bin_i('36893488147419103232'); //2^65
?>
Output: A 1 followed by 65 zeros:
100000000000000000000000000000000000000000000000000000000000000000
回答2:
There is a function to reverse a string strrev
$dec=101;
$binStr = '';
while ($dec>=1){
$bin = $dec % 2;
$dec = round($dec/2, 0, PHP_ROUND_HALF_DOWN);
$binStr .= $bin;
}
$binStr = strrev($binStr);
echo $binStr;
回答3:
try this:
$dec = 101;
$bos = NULL;
while ($dec>=1){ $bin = $dec % 2; $dec = round($dec/2, 0,
PHP_ROUND_HALF_DOWN);
$bos .= $bin;
}
echo strrev($bos);
来源:https://stackoverflow.com/questions/25017724/php-decimal-to-binary-conversion-without-decbin