0

I have this function which converts numbers from decimal to 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--)
    {
        a .= substr($b,$i,$i +1);
    }*/
    return $b;

}
?>

My problem is that it will return the string:

010010100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

I wish to return only:

0100101

How can I achieve this?

0

4 Answers 4

5

$num = $num / 2; probably does fractional division (implicitly converting to float), causing $num to approach 0 but taking a very long time to get there. Make it $num = floor($num / 2); to round it back down to an integer.

Note that there's also decbin(), the built-in method for achieving this.


Exemplary (but superfluous):

function DecimalTOBinary($num)
{
    return decbin($num);
}
Sign up to request clarification or add additional context in comments.

Comments

2

If you want that function for practical reasons, do what @Core Xii says. If you want to implement that function to learn, you should use the floor function: $num = floor($num/2), because PHP thinks that $num is a float and doesn't divide it as an integer.

Also, you'll want to return strrev($b), because your digits will be reversed.

Comments

0

This function will do what you want:

<?php
function DecimalToBinary($num) {
    $i = "";
    while (floor($num) > 0) {
        $i .= $num % 2;
        $num /= 2;
    }
    return strrev($i);
}

The main changes are:

  • Flooring the number in while loop check
  • Reversing digits.
  • Removed unnecessary variables.

Comments

0

Try this code this solution done with recursive function:

 function getBinary($num) {
 $remainder = '';
 $remainder = $num % 2;
 $num = floor($num / 2);  
 if ($num>=1)
  {
    $remainder .= getBinary($num);
  }
  
 return $remainder;
} 
echo getBinary(10);

1 Comment

It's best to explain your answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.