Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- if ($_POST['post'] == "true")
- {
- $decimal = $_POST['dec_num'];
- $decimal = round($decimal);
- $divisor = 0;
- $remainder = 0;
- $remainders = array();
- $iteration = 0;
- $i = 0;
- $next = $decimal;
- if ($decimal > 256)
- die("<b>ERROR</b>: Overflow");
- if ($decimal < 0)
- die("<b>ERROR</b>: Negative Number");
- for(;;)
- {
- for(;;)
- {
- // highest divisor found, but it's too high, so go back a step
- if ($divisor > $next)
- {
- $divisor /= 2;
- $iteration--;
- break;
- }
- $iteration++;
- $divisor = 2 * $iteration;
- }
- $remainder = $next - (2 * $iteration);
- // failsafe
- if ($remainder > 1)
- die("<b>ERROR</b>: Invalid Remainder");
- $remainders[$i] = $remainder;
- // cannot apply division algorithm anymore
- if ($iteration == 0)
- break;
- $divisor = 1;
- $i++;
- $next = $iteration;
- $iteration = 0;
- }
- $sizeof = count($remainders);
- for ($k = 8; $k > $sizeof; $k--)
- $bin_num .= 0;
- for ($j = $sizeof; $j + 1 > 0; $j--)
- $bin_num .= $remainders[$j];
- /*
- for ($j = 0; $j < $i + 1; $j++)
- echo "remainders[$j]:" . $remainders[$j] . "<br>";
- */
- }
- ?>
- <h1>Decimal to Binary Converter</h1>
- <h2>Unsigned, 8 bits</h2>
- <h3>Integers 0 - 255</h3>
- <form id="conv_form" name="conv_form" method="POST">
- <b>Decimal Number</b>: <input type="text" name="dec_num" id="dec_num" maxlength="3" size="1" class="input"><br /><br />
- <input type="hidden" name="post" value="true">
- <input type="submit" value="Convert" id="conv_but" class="input">
- <?php
- if (isset($bin_num))
- echo "<br /><br /><b>Your 8-bit Binary Number is</b>: " . $bin_num;
- ?>
Add Comment
Please, Sign In to add comment