5
PHP Program to Add Two Binary Numbers
source link: https://www.geeksforgeeks.org/php-program-to-add-two-binary-numbers/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
PHP Program to Add Two Binary Numbers
Discuss
Courses
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:
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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!
Last Updated :
12 Dec, 2023
Like Article
Save Article
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK