Home  >  Article  >  Backend Development  >  How to convert php string to hexadecimal string

How to convert php string to hexadecimal string

藏色散人
藏色散人Original
2020-10-07 00:30:004059browse

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.

How to convert php string to hexadecimal string

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=&#39;&#39;;
        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=&#39;&#39;;
//        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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn