ProblematicSolution
ProblematicSolution

Reputation: 41

Write own function to convert decimal numbers to binary

I am trying to write my own function to convert decimal numbers to binary. I know there are build-in functions for this, but I'm trying to write my own here, which I can't get to work correctly.

Right now the code below doesn't give me any output. I'm new to PHP so ever hint where I went wrong would help.

Code:

<?php

    {

    $dec = 0;

    if(isset($_POST['num'])) {
        $dec = $_POST['num'];
    }

    decimal_binary($dec);
    echo $dec;

    }

function decimal_binary($dec) 
{

    $rem;
    $i = 1;
    $binary = 0;
    while ($dec != 0)
    {
        $rem = $dec % 2;
        $dec /= 2;
        $binary += $rem * i;
        $i *= 10;
    }

    $dec = $binary;
    echo $binary;

    return decimal_binary($dec);

}


?>
<html> 
    <body>

    <form action="3.php" method="POST">
        Integer <input type="number" name="num">
        <input type="submit">
    </form>

    </body>
</html>

Upvotes: 1

Views: 2966

Answers (1)

Zeke
Zeke

Reputation: 1291

You just made an infinite recursion, I mean you are calling the function over and over again with the result as parameter.

- EDIT -

So your function doesn't work, but I came up with this one, and it does work. Try it out:

function decimal_binary($dec){
    $binary;
    while($dec >= 1){
        $rem = $dec % 2;
        $dec /= 2;
        $binary = $rem.$binary;
    }
    if($binary == null){
        $binary = 0;
    }
    return $binary;
}

- END EDIT -

Also, you need to place the function before you call it, and when you call it, you need to assign it to a variable so that you can use the output value in other parts of your code:

<?php

// function here

$dec = 0;
if(isset($_POST['num'])){
    $dec = $_POST['num'];
}

$bin = decimal_binary($dec);
?>

Upvotes: 1

Related Questions