Open In App

How to Convert Decimal to Hexadecimal in PHP ?

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

In this article, we will see How to convert a Decimal Number to a Hexadecimal Number using PHP. The Number System is basically used for the conversion of 1 number type into another, which, in turn, makes it possible to store and manipulate data electronically(i.e. 0’s & 1’s) using digital circuits.

Example: The below examples illustrate the Decimal to Hexadecimal Conversion:

Input: 1023
Output: 3FF

Input: 46434
Output: B562

There are 2 methods to convert the Decimal value to the Hexadecimal value:

Using dechex() Function

The dechex() function is used to convert the given decimal number to an equivalent hexadecimal number. The word ‘dechex’ in the name of the function stands for decimal to hexadecimal. The largest number that can be converted is 4294967295 in decimal resulting in “ffffffff”.

Syntax

string dechex($value);

Example: This example illustrates the basic conversion of Decimal to Hexadecimal using built-in Function in PHP.

PHP




<?php
  
function decToHexConverter($num)
{
    $hex = dechex($num);
    return $hex;
}
  
$num = 8906;
$hexVal = decToHexConverter($num);
  
echo "Hexadecimal Value: " . strtoupper($hexVal);
  
?>


Output:

Hexadecimal Value: 22CA

Using Conversion Algorithm

We will use the conversion algorithm to convert the Decimal Value to an equivalent Hexadecimal Value in PHP. To convert the decimal to hexadecimal, we will use remainder and division method.

Example: This example illustrates the basic conversion of Decimal to Hexadecimal using the remainder and division method in PHP.

PHP




<?php
  
function decToHexConverter($n)
{
    $hex;
  
    while ($n > 0) {
        $rem = $n % 16;
        if ($rem < 10) {
            $hex = $rem . $hex;
        } else {
            $hex = chr($rem + 55) . $hex;
        }
        $n = (int) ($n / 16);
    }
  
    return $hex;
}
  
// Driver Code
$num = 7655;
  
echo "Hexadecimal Value: " . decToHexConverter($num);
?>


Output

Hexadecimal Value: 1DE7



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads