Austin's Number to Binary Demo

This shows how one can take a number typed into a form and change each digit of that number into binary (4 bits per digit).


Code follows

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Austin String Example</title>
    <link rel="stylesheet" href="css/styles.css">
</head>
<body>

<div class="page">

    <p class="nav"><a href="../index.php">Home</a></p>


    <?php

    error_reporting
(E_ALL);    // set error reporting to all

    
?>

    <h1>Austin's Number to Binary Demo</h1>

    <p>
        This shows how one can take a number typed into a form and
        change each digit of that number into binary (4 bits per digit).
    </p>

    <form action="austin-string-example.php" method="POST">

        <label for="numberInput">Enter a number</label>
        <input type="text" id="numberInput" name="numberInput" size="36">

        <input type="submit" name="postSubmit" value="Submit">

    </form>

    <?php

    
// variables

    
$userInput = '';
    
$digits = '';
    
$binary = '';

    
// check if the form was submitted

    
if (isset($_POST['numberInput']))
    {
        
$userInput = trim($_POST['numberInput']);   // get what they typed in

        // take out any spaces and dashes

        
$digits = str_replace(" ", "", $userInput);
        
$digits = str_replace("-", "", $digits);

        
// make sure they typed something and it is only digits

        
if ($digits != '' && ctype_digit($digits))
        {
            
// loop through the digits one at a time

            
for ($i = 0; $i < strlen($digits); $i++)
            {
                
$oneDigit = (int)$digits[$i];          // grab one digit
                
$bits = decbin($oneDigit);             // change it to binary
                
$bits = str_pad($bits, 4, "0", STR_PAD_LEFT);   // make it 4 bits long

                
$binary .= $bits . " ";                // append to $binary
            
}

            echo(
"<p>You typed: " . htmlspecialchars($userInput) . "</p>");
            echo(
"<p>Binary: " . $binary . "</p>");
        }
        else
        {
            echo(
"<p>Please enter a valid number.</p>");
        }
    }

    
?>

    <hr>

    <h2>Code follows</h2>

    <div class="code"><?php highlight_file(__FILE__); ?></div>

    <p class="nav nav-foot"><a href="../index.php">Home</a></p>

</div>

</body>
</html>