In PHP, you can convert decimal to hexadecimal by using the built-in function dechex() or base_convert() function. The following article will introduce to you how the dechex() and base_convert() functions convert decimal to hexadecimal. I hope it will be helpful to you. [Video tutorial recommendation: PHP tutorial]
Method 1: Use the dechex() function to convert decimal to hexadecimal
The dechex() function is a built-in function in PHP that is used to convert a given decimal number into its equivalent hexadecimal number. The word "dechex" in the function name stands for decimal to hexadecimal.
Note:
● The dechex() function only applies to unsigned numbers. If the argument passed to it is negative, then it will treat it as an unsigned number.
●The maximum number that can be converted is 4294967295 (decimal), and the result is "ffffffff".
Example:Convert decimal to hexadecimal
<?php header("content-type:text/html;charset=utf-8"); $num1=10; $num2=47; $num3=4294967295; echo "十进制 ".$num1." 转换成十六进制 ".dechex($num1)."<br>"; echo "十进制 ".$num2." 转换成十六进制 ".dechex($num2)."<br>"; echo "十进制 ".$num3." 转换成十六进制 ".dechex($num3)."<br>"; ?>
Output:
Method 2: Use the base_convert() function to convert decimal to hexadecimal
The base_convert() function can convert numbers between any bases.
Example 1: Convert decimal to hexadecimal
<?php header("content-type:text/html;charset=utf-8"); $num1=10; $num2=47; echo "十进制 ".$num1." 转换成十六进制 ".base_convert($num1,10,16)."<br>"; echo "十进制 ".$num2." 转换成十六进制 ".base_convert($num2,10,16)."<br>"; ?>
Output:
十进制 10 转换成十六进制 a 十进制 47 转换成十六进制 2f
Example 2: Convert decimal Convert hexadecimal to decimal
<?php header("content-type:text/html;charset=utf-8"); $hex="16e7"; $dec =base_convert($hex,16,10); echo "十六进制 $hex 转换成十进制 $dec <br>"; ?>
Output:
十六进制 16e7 转换成十进制 5863
Example 3:Convert octal to decimal
<?php header("content-type:text/html;charset=utf-8"); $oct = "0031"; $dec = base_convert($oct,8,10); echo "八进制 $oct 转换成十进制 $dec <br>"; ?>
Output:
八进制 0031 转换成十进制 25
The above is the entire content of this article, I hope it will be helpful to everyone's study. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !
The above is the detailed content of How to convert decimal to hexadecimal in PHP? (code example). For more information, please follow other related articles on the PHP Chinese website!