| by Arround The Web | No comments

How to Use Dechex() Function in PHP

The dechex() is a built-in simple PHP function that allows you to quickly convert a decimal value into its corresponding hexadecimal value. This function is supported on PHP versions 4 and later. It can accept a decimal value as an argument and return its hexadecimal equivalent value. It is useful in cases where you have to manipulate binary data or perform encoding or decoding-related tasks.

Syntax

The PHP dechex() function follows a simple syntax that is given below:

dechex(dec_num)

The above syntax shows that the function accepts only one mandatory parameter. This function does not require any optional parameter.

Here:

  • dec_num: A mandatory argument that specifies a decimal value that we need to convert into a hexadecimal value.
  • Return Value: The dechex() function returns a string that indicates a hexadecimal value equivalent to the given decimal value.

Example 1

In this example, the decimal value is set as a variable. The decimal number is then passed as an argument to the dechex() function, which performs the conversion from decimal to hexadecimal. The hexadecimal number is then displayed on the screen.

<?php

$decimal_number = 1024;

// Use the dechex() function to convert a given decimal number to hexadecimal number.

$hex_number = dechex($decimal_number);

// Output the hexadecimal number

echo "The converted decimal number to hexadecimal number is: ", $hex_number;

?>

Example 2

In this example, multiple decimal values are set as variables. Each decimal number is then passed as the argument to the dechex() function, which performs the conversion from a decimal value to its equivalent hexadecimal value. The hexadecimal numbers corresponding to their decimal values are then displayed on the screen.

<?php

$dec_val1= 100;

$dec_val2=6;

$dec_val3=23147;

$hex1=dechex($dec_val1);

$hex2=dechex($dec_val2);

$hex3=dechex($dec_val3);

echo "Hex value of $dec_val1 is $hex1 \n";

echo "Hex value of $dec_val2 is $hex2 \n";

echo "Hex value of $dec_val3 is $hex3 \n";

?>

Conclusion

A built-in dechex() function in PHP allows us the conversion of a decimal value into a hexadecimal value. This is an essential tool used by PHP developers to develop such applications that convert a decimal value to a hexadecimal value. This function takes a decimal number as an input and returns a decimal number that is equivalent to the given decimal number. This tutorial explored the working of the dechex() function in PHP using examples.

Share Button

Source: linuxhint.com

Leave a Reply