In PHP programming, there is often a need to convert numerical values between different digits, especially the conversion between decimal and hexadecimal. PHP provides two very convenient built-in functions hexdec() and dechex() , which are used to convert hexadecimal numbers to decimal numbers and convert decimal numbers to hexadecimal numbers, respectively.
The hexdec() function takes a hex string as an argument and returns the corresponding decimal integer. When using, just pass in a string containing hexadecimal numbers.
<?php
$hex = "1A3F";
$decimal = hexdec($hex);
echo "Hexadecimal number {$hex} Convert to decimal is: {$decimal}";
?>
Output:
Hexadecimal number 1A3F Convert to decimal is: 6719
The dechex() function takes a decimal integer as an argument and returns the corresponding hexadecimal string.
<?php
$decimal = 6719;
$hex = dechex($decimal);
echo "Decimal number {$decimal} Convert to hexadecimal is: {$hex}";
?>
Output:
Decimal number 6719 Convert to hexadecimal is: 1a3f
Note that the returned hexadecimal string is lowercase by default. If uppercase is required, you can combine the strtoupper() function:
<?php
$hex = strtoupper(dechex($decimal));
echo "Capital hexadecimal: {$hex}";
?>
Output:
Capital hexadecimal: 1A3F
Suppose there is a simple web form where the user enters a hexadecimal number and displays the corresponding decimal number after submission, and vice versa.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!empty($_POST['hex'])) {
$hex = $_POST['hex'];
$decimal = hexdec($hex);
echo "<p>hexadecimal {$hex} Convert to decimal is {$decimal}</p>";
}
if (!empty($_POST['decimal'])) {
$decimal = (int)$_POST['decimal'];
$hex = dechex($decimal);
echo "<p>Decimal {$decimal} Convert to hexadecimal is {$hex}</p>";
}
}
?>
<form method="post" action="https://gitbox.net/convert.php">
<label>hexadecimal: <input type="text" name="hex"></label><br>
<label>Decimal: <input type="text" name="decimal"></label><br>
<input type="submit" value="Convert">
</form>
In this example, the user can enter any hexadecimal or decimal number through the form, and after submission, the background will perform corresponding conversion and display the results.