In programming, you often encounter the need to convert a string to hexadecimal situation, or you need to convert a hexadecimal number into a string. Today we will introduce how to use PHP to write a program to convert a string to hexadecimal and output the string in reverse.
First, we need to write a function to convert a string to hexadecimal. The following is a PHP code example:
function strToHex($string){ $hex = ''; for ($i=0; $i < strlen($string); $i ){ $hex .= dechex(ord($string[$i])); } return $hex; } // test $str = "Hello, World!"; $hex = strToHex($str); echo "Convert string to hexadecimal:".$hex;
In the above code, the strToHex
function accepts a string as a parameter, and then uses ord
The function converts each character into an ASCII value, and then uses the dechex
function to convert the ASCII value into hexadecimal representation. Finally, all the hexadecimal strings are concatenated and output.
Next, we need to write a function to convert hexadecimal to string. The code is as follows:
function hexToStr($hex){ $string = ''; for ($i=0; $i < strlen($hex)-1; $i =2){ $string .= chr(hexdec($hex[$i].$hex[$i 1])); } return $string; } // test $hex = "48656c6c6f2c20576f726c6421"; $str = hexToStr($hex); echo "Convert hexadecimal to string:".$str;
In the above code, the hexToStr
function accepts a hexadecimal string as a parameter, and then converts two consecutive Combine the hexadecimal characters into an ASCII value, and then use the chr
function to convert the ASCII value into the corresponding character. Concatenate all characters to get the final string output.
Integrate the above two functions into a complete PHP script, as shown below:
function strToHex($string){ $hex = ''; for ($i=0; $i < strlen($string); $i ){ $hex .= dechex(ord($string[$i])); } return $hex; } function hexToStr($hex){ $string = ''; for ($i=0; $i < strlen($hex)-1; $i =2){ $string .= chr(hexdec($hex[$i].$hex[$i 1])); } return $string; } // test $str = "Hello, World!"; $hex = strToHex($str); echo "Convert string to hexadecimal: ".$hex." "; $reversedStr = hexToStr($hex); echo "Reverse output string:".$reversedStr;
Through the above code example, we can realize the mutual conversion between string and hexadecimal, and can reverse the string output. Such functions are often used in data encryption, data transmission, etc. I hope it will be helpful to you.
The above is the detailed content of Write a program in PHP to convert hexadecimal and reverse output string. For more information, please follow other related articles on the PHP Chinese website!