while loop - Converting a decimal number to binary in PHP -
i have function converts numbers decimal binary.
<?php function decimaltobinary($num) { $a = ""; $b = ""; $x = 0; while ($num !=0) { $b .= $num % 2; $num = $num /2; } /* for($i = strlen($b) -1;$i >=0;$i--) { .= substr($b,$i,$i +1); }*/ return $b; } ?> my problem return string:
010010100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 i wish return only:
0100101 how can achieve this?
$num = $num / 2; fractional division (implicitly converting float), causing $num approach 0 taking long time there. make $num = floor($num / 2); round down integer.
note there's decbin(), built-in method achieving this.
exemplary (but superfluous):
function decimaltobinary($num) { return decbin($num); }
Comments
Post a Comment