PHP将字符串转换为十六进制,并将十六进制转换为字符串

我在PHP的这2种类型之间进行转换时遇到问题。这是我在谷歌搜索的代码


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;

}

我检查了一下,并在使用XOR加密时发现了这一点。


我有字符串"this is the test",在与键进行XOR之后,结果在string中↕↑↔§P↔§P ♫§T↕§↕。之后,我尝试通过功能strToHex()将其转换为十六进制,并得到了这些12181d15501d15500e15541215712。然后,我使用功能hexToStr()进行了测试,然后得到了↕↑↔§P↔§P♫§T↕§q。那么,该怎么办才能解决这个问题呢?转换这2个样式值时为什么会出错?


手掌心
浏览 2730回答 3
3回答

子衿沉夜

对于那些最终来到这里并且只是在寻找(二进制)字符串的十六进制表示的人。bin2hex("that's all you need");# 74686174277320616c6c20796f75206e656564hex2bin('74686174277320616c6c20796f75206e656564');# that's all you need

守候你守候我

function hexToStr($hex){&nbsp; &nbsp; // Remove spaces if the hex string has spaces&nbsp; &nbsp; $hex = str_replace(' ', '', $hex);&nbsp; &nbsp; return hex2bin($hex);}// Test it&nbsp;$hex&nbsp; &nbsp; = "53 44 43 30 30 32 30 30 30 31 37 33";echo hexToStr($hex); // SDC002000173/**&nbsp;* Test Hex To string with PHP UNIT&nbsp;* @param&nbsp; string $value&nbsp;* @return&nbsp;&nbsp;*/public function testHexToString(){&nbsp; &nbsp; $string = 'SDC002000173';&nbsp; &nbsp; $hex&nbsp; &nbsp; = "53 44 43 30 30 32 30 30 30 31 37 33";&nbsp; &nbsp; $result = hexToStr($hex);&nbsp; &nbsp; $this->assertEquals($result,$string);}
打开App,查看更多内容
随时随地看视频慕课网APP