Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP convert string to hex and hex to string

Tags:

string

php

hex

I got the problem when convert between this 2 type in PHP. This is the code I searched in google

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; } 

I check it and found out this when I use XOR to encrypt.

I have the string "this is the test", after XOR with a key, I have the result in string ↕↑↔§P↔§P ♫§T↕§↕. After that, I tried to convert it to hex by function strToHex() and I got these 12181d15501d15500e15541215712. Then, I tested with the function hexToStr() and I have ↕↑↔§P↔§P♫§T↕§q. So, what should I do to solve this problem? Why does it wrong when I convert this 2 style value?

like image 873
JoeNguyen Avatar asked Feb 03 '13 16:02

JoeNguyen


1 Answers

For people that end up here and are just looking for the hex representation of a (binary) string.

bin2hex("that's all you need"); # 74686174277320616c6c20796f75206e656564  hex2bin('74686174277320616c6c20796f75206e656564'); # that's all you need 

Doc: bin2hex, hex2bin.

like image 160
Philippe Gerber Avatar answered Sep 23 '22 23:09

Philippe Gerber