PHP Program to Add Two Binary Numbers
Last Updated :
12 Dec, 2023
Improve
Given Two binary numbers, the task is to add two binary numbers in PHP.
Examples:
Input: num1 = '1001', num2 = '1010'
Output: 10011
Input: num1 = '1011', num2 = '1101'
Output: 11000
There are two methods to add to binary numbers, these are:
Table of Content
Using bindec() and decbin() Functions
In this approach, first we convert binary numbers to decimal number, then adding them, and then converting the sum to binary.
Example:
<?php
function addBinary($bin1, $bin2) {
$dec1 = bindec($bin1);
$dec2 = bindec($bin2);
$sumDec = $dec1 + $dec2;
$sumBin = decbin($sumDec);
return $sumBin;
}
$num1 = '1011';
$num2 = '1101';
echo "Decimal Value: " . addBinary($num1, $num2);
?>
Output
Decimal Value: 11000
Using base_convert() Function
In this method, we use base_convert() method to convert binary to decimal, and then perform addition operation, and the last, convert the result back to binary using base_convert() function.
Example:
<?php
function addBinary($bin1, $bin2) {
$dec1 = base_convert($bin1, 2, 10);
$dec2 = base_convert($bin2, 2, 10);
$sumDec = $dec1 + $dec2;
$sumBin = base_convert($sumDec, 10, 2);
return $sumBin;
}
$num1 = '1101';
$num2 = '1010';
echo "Decimal Value: " . addBinary($num1, $num2);
?>
Output
Decimal Value: 10111