You are here: Home / Topics / How to convert decimal numbers to binary in PHP

How to convert decimal numbers to binary in PHP

Filed under: PHP on 2022-11-15 10:45:25

This program is written is PHP and HTML to show how to convert decimal number to binary number. 

Note- there is a inbuilt function in PHP which is used for converting decimal numbers to binary. decbin() function is used for this purpose. 

Program::

// To convert Decimal number into Binary number
<html>
<head>
<title>PHP Program To convert Decimal number into Binary number</title>
</head>
<body>
<form method="post">
<table border="0">
<tr>
<td> <input type="text" name="num" value="" placeholder="Enter decimal number"/> </td>
</tr>
<tr>
<td> <input type="submit" name="submit" value="Submit"/> </td>
</tr>
</table>
</form>
<?php
if(isset($_POST['submit']))
{
$n = $_POST['num'];
$num = $n;
$n1 = $n;
$binary;
$i = 0; //Count for binary array
while ($n > 0)
{
$binary[$i] = $n % 2; //Remainder will stored in binary array
$n = (int)($n / 2);
$i++; //Count increment
}
echo "The Decimal number is : ".$num ;
echo "The Equivalent Binary number is : ";
for ($j = $i - 1; $j >= 0; $j--)
echo $binary[$j];
return 0;
}
?>
</body>
</html>

About Author:
M
Mr. Dubey     View Profile
Founder and CEO of MCQ Buddy. I just like to help others. This portal helps students in getting study material free.