Skip to content

Instantly share code, notes, and snippets.

@jatkins
Created May 5, 2011 02:46
Show Gist options
  • Save jatkins/956448 to your computer and use it in GitHub Desktop.
Save jatkins/956448 to your computer and use it in GitHub Desktop.
Simple base converter
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>
@jatkins
Copy link
Author

jatkins commented May 5, 2011

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment