189. PHP Program to Convert Integer into its equivalent number in another base.
How does this program work?
- This program is used to convert given Integer into its equivalent number in another base using PHP.
- That means convert number with base value 10 to base value 2, 8 and 16.
- The integer entered by user will store in one variable. Divide that number by 2.
- Store the remainder when the number is divided by 2 in an array, Repeat the above step until the number is greater than zero.
Here is the code
<html>
<head>
<title>PHP Program To convert Integer into another base</title>
</head>
<body>
<form method="post">
<table border="0">
<tr>
<td> <input type="text" name="name1" value="" placeholder="Enter number"/> </td>
</tr>
<tr>
<td> <input type="text" name="name2" value="" placeholder="Enter base"/> </td>
</tr>
<tr>
<td> <input type="submit" name="submit" value="Submit"/> </td>
</tr>
</table>
</form>
<?php
function val($c)
{
if ($c >= '0' && $c <= '9')
return ord($c) - ord('0');
else
return ord($c) - ord('A') + 10;
}
function toDeci($str, $base)
{
$len = strlen($str);
$power = 1; // Initialize power of base
$num = 0; // Initialize result
for ($i = $len - 1; $i >= 0; $i--)
{
// A digit in input number must be less than number's base
if (val($str[$i]) >= $base)
{
echo("Invalid Number");
return -1;
}
$num += val($str[$i]) * $power;
$power = $power * $base;
}
return $num;
}
if(isset($_POST['submit']))
{
$str = $_POST['name1'];
$base = $_POST['name2'];
echo ("Decimal equivalent of $str " . "in base $base is " . toDeci($str, $base) );
}
?>
</body>
</html>