6

Binary to Decimal Conversion in PHP

 9 months ago
source link: https://www.geeksforgeeks.org/binary-to-decimal-conversion-in-php/
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.
neoserver,ios ssh client

Binary to Decimal Conversion in PHP

Discuss
Courses

Given a binary number, the task is to convert Binary to Decimal Number in PHP.

Examples:

Input: 1010
Output: 10

Input: 11001
Output: 25

There are different methods to convert Binary to Decimal Numbers, These are:

Using bindec() Function

The bindec() function returns the decimal equivalent of the binary number. It accepts a string argument i.e binary number and returns decimal equivalent.

Syntax:

bindec( $bin_num );

Example:

<?php
$binNum = 110010;
$decNum = bindec($binNum);
echo "Decimal Number: " . $decNum;
?>
Output
Decimal Number: 50

Using base_convert() Function

The base_convert() function converts a given number in an arbitrary base to a desired base. In this case, we use 2 as fromBase and 10 as desireBase.

Syntax:

string base_convert($inpNumber, $fromBase, $desBase)

Using Conversion AlgorithmExample:

<?php
$binNum = 110010;
$decNum = base_convert($binNum, 2, 10);
echo "Decimal Number: " . $decNum;
?>
Output
Decimal Number: 50

Using Conversion Algorithm

In this case, we use mathematical conversion algorithm to convert binary to its decimal equivalent. Here, we convert a binary number to decimal by iterating through each bit and summing up the corresponding powers of 2.

<?php
function binToDec($binNum) {
$decNum = 0;
$len = strlen($binNum);
for ($i = 0; $i < $len; $i++) {
$decNum += (int)$binNum[$i] * pow(2, $len - $i - 1);
}
return $decNum;
}
$binNum = '110010';
$decNum = binToDec($binNum);
echo "Decimal Number: " . $decNum;
?>
Output
Decimal Number: 50
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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK