Created
May 5, 2011 02:46
-
-
Save jatkins/956448 to your computer and use it in GitHub Desktop.
Simple base converter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Decimal: <input type="text" name="decimal"/> | |
Converting to base: | |
<select name="base"> | |
<option value="2">2 - Binary</option> | |
<option value="8">8 - Octal</option> | |
<option value="16">16 - Hexadecimal</option> | |
</select> | |
<input type="submit" /> | |
</form> | |
</p> | |
<? | |
$keys = array(0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F'); // Values to convert to, this is a hack of a way to do base conversion but it works. | |
if(is_numeric($_POST["decimal"])){ // Make sure the input is a number | |
// Have to convert from str to int! | |
$dec = intval($_POST["decimal"]); | |
$base = intval($_POST["base"]); | |
// Lets do Math!!!!! | |
while(intval($dec) != 0) { | |
$output .= strval($keys[$dec % $base]); | |
$dec /= $base; | |
} | |
// Switch statements make code nasty, but in this case it was faster to use. | |
switch($base) { | |
case 2: | |
$base_w = "binary"; | |
$base_m = "0b"; | |
break; | |
case 8: | |
$base_w = "octal"; | |
$base_m = "0o"; | |
break; | |
case 16: | |
$base_w = "hexadecimal"; | |
$base_m = "0x"; | |
break; | |
} | |
// Display the results | |
echo $_POST["decimal"] . " in " . $base_w . " is " . $base_m . strrev($output); | |
} elseif(isset($_POST["decimal"])) { | |
echo "That is not a number you douchewank!"; | |
} | |
?> | |
<p> | |
<a href="http://gist.github.com/956448">Source Code</a> | |
</p> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a simple base converter, I wrote it in about 10 minutes so its not as clean as it could be. Live demo at http://jacobatkins.com/base.php