Home > Article > Backend Development > How to convert php string to hexadecimal string
How to convert php string to hexadecimal: first create a PHP sample file; then convert the string to hexadecimal through the String2Hex method; and finally return the conversion result through return.
Recommended: "PHP Video Tutorial"
Conversion of PHP strings and hexadecimal encoding
php string is decimal
/** **字符串转16进制 **/ public function String2Hex($string){ $hex=''; for ($i=0; $i < strlen($string); $i++){ $hex .= dechex(ord($string[$i])); } return $hex; } /** **16进制转字符串 **/ public function Hex2String($hex){ $string=''; for ($i=0; $i < strlen($hex)-1; $i+=2){ $string .= chr(hexdec($hex[$i].$hex[$i+1])); } return $string; } // example: $hex = String2Hex("test sentence..."); // $hex contains 746573742073656e74656e63652e2e2e echo Hex2String($hex); // outputs: test sentenc
I found a problem when doing aes encryption. I found that when converting the string to hexadecimal, there will be a problem that the number of converted data does not match. It can be modified as Try the following:
public function String2Hex($string){ $hex=''; // for ($i=0; $i < strlen($string); $i++){ // $hex .= dechex(ord($string[$i])); // } $hex = bin2hex($string); return $hex; }
The above is the detailed content of How to convert php string to hexadecimal string. For more information, please follow other related articles on the PHP Chinese website!