Open In App

Decimal to Binary Conversion in PHP

Last Updated : 28 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a Decimal Number, and the task is to convert a given Decimal Number to a Binary Number using PHP.

Examples:

Input: 10
Output: 1010

Input: 25
Output: 11001

There are different methods to convert the Decimal to a Binary number, these are:

Using decbin() Function

The decbin() function converts the given decimal number to the binary number. It returns a string containing a binary representation of the given decimal number argument. decbin stands for decimal to binary.

Syntax:

string decbin( $value )

Example:

PHP




<?php
 
$decNum = 42;
 
$binNum = decbin($decNum);
 
echo "Binary Number: " . $binNum;
 
?>


Output

Binary Number: 101010

Using Conversion Algorithm

We will use the conversion algorithm to convert the Decimal Number to its equivalent Binary Number in PHP. We will define a custom function decimalToBinary that takes a decimal number as input and iteratively divides it by 2, collecting the remainders at each step. Concatenate these remainders in reverse order to get the Binary number. The loop continues until the decimal number becomes zero.

Example:

PHP




<?php
 
// Function to convert Decimanl number to
// Binary Number
function decimalToBinary($decNum) {
    $binNum = '';
    while ($decNum > 0) {
        $rem = $decNum % 2;
        $binNum = $rem . $binNum;
        $decNum = (int)($decNum / 2);
    }
    return $binNum !== '' ? $binNum : '0';
}
 
$decNum = 25;
 
$binNum = decimalToBinary($decNum);
 
echo "Binary Number: " . $binNum;
 
?>
<?php


Output

Binary Number: 11001

Using Recursion

We will use Recursive function to convert Decimal number to Binary Number in PHP. First, we declare a recursive function decimalToBinary that checks if the input number is zero, it returns ‘0’. Otherwise, it makes a recursive call with the integer division of the number by 2 and appends the remainder to the result.

PHP




<?php
 
// Recursive Function to Convert Decimal
// to Binary Number
function decimalToBinary($decNum) {
    if ($decNum == 0) {
        return '0';
    } else {
        return decimalToBinary(
            (int)($decNum / 2)) . ($decNum % 2);
    }
}
 
// Driver Code
$decNum = 25;
 
$binNum = decimalToBinary($decNum);
$binNum = ltrim($binNum, "0");
 
echo "Binary Number: " . $binNum;
 
?>


Output

Binary Number: 11001



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads