Kamis, 09 Agustus 2012

Coding PHP Konversi Bilangan Desimal ke Biner


Berikut ini adalah coding untuk mengkonversikan bilangan desimal menjadi biner menggunakan PHP web page :
<?php
if (isset($_POST['decimal'])) { //apakah data ter-submit ?
    $decimal = $_POST['decimal'];
    $original = $_POST['decimal'];
    $binary='';
    if (preg_match('/[^0-9]/',$decimal)) { //memastikan input
        die("Maaf. Inputan salah..");
    }
    else {
        while ($decimal > 0) { //Looping memutuskan apakah 1 atau 0
            if ($decimal%2 == 0) { // menambah 0
                $binary .= 0; //$binary=0+$binary;
                $decimal /= 2;//$binary=$binary/2;
            }
            else { // menambah 1
                $binary .=1;//$binary=1+$binary;
                $decimal = ($decimal/2)-0.5;
            }
        }
        $result = strrev($binary);//hasile diwalik
        echo "Bilangan $original (desimal) dalam biner adalah $result.
        <a href='konversi_inputan_ke_biner.php'>Back</a> to the script";
    }
}
else {
?>
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
    </head>
    <body>
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>"
              method="POST">
            <h3>Masukkan bilangan Desimal disini (cepat!!):
            </h3><input type="text" size="50" name="decimal">
            <input type="submit" value="Konversikan!">
        </form>
        <?php
        echo "<br>",$_SERVER['PHP_SELF'];
        ?>
    </body>
</html>
<?php
}
?>


Hasil Jadi dari program ini :



Tidak ada komentar:

Posting Komentar