Hexadecimal to Decimal Conversion in PHP
Last Updated :
12 Dec, 2023
Given a Hexadecimal Number, and the task is to convert Hexadecimal to a Decimal Number using PHP.
Examples:
Input: hexNum = '1A'
Output:
Input: hexNum = '634E24'
Output: 6508068
There are three different methods to convert Hexadecimal to Decimal number, these are:
Using hexdec() Function
The hexdec() function converts a hexadecimal number to a decimal number. This function converts numbers that are too large to fit into the integer type, larger values are returned as a float in that case. If hexdec() encounters any non-hexadecimal characters, it ignores them.
Syntax:
hexdec( $value )
Example:
PHP
<?php
function hexToDec( $hex ) {
return hexdec( $hex );
}
$hexNum = '1A' ;
$decimalNum = hexToDec( $hexNum );
echo "Decimal Value: " . $decimalNum ;
?>
|
Using base_convert() Function
The base_convert() function converts a given number to the desired base. Both the base should be between 2 and 32 and bases with digits greater than 10 are represented with letters a-z i.e 10 is represented as a, 11 is represented as b and 35 is represented as z.
Syntax:
string base_convert($inpNumber, $fromBase, $desBase)
Example:
PHP
<?php
function hexToDec( $hex ) {
return base_convert ( $hex , 16, 10);
}
$hexNum = '634E24' ;
$decimalNum = hexToDec( $hexNum );
echo "Decimal Value: " . $decimalNum ;
?>
|
Output
Decimal Value: 6508068
Using for Loop
In this approach, we perform mathematical operation with for loop to convert the Hexadecimal number to Decimal equivalent.
Example:
PHP
<?php
function hexToDec( $hex ) {
$decimal = 0;
$length = strlen ( $hex );
for ( $i = 0; $i < $length ; $i ++) {
$digit = $hex [ $i ];
$decimal = $decimal * 16 + hexdec( $digit );
}
return $decimal ;
}
$hexNum = '1A' ;
$decimalNum = hexToDec( $hexNum );
echo "Decimal Value: " . $decimalNum ;
?>
|
Share your thoughts in the comments
Please Login to comment...