All for Joomla All for Webmasters

Let's Play With Coding…

String to Hex & Hex to String Conversion in PHP

Hi Guys I just gone through a situation need to convert string to Hex but unfortunatly not found any Pre-build function in PHP but don’t worry today I would like to share you a function which solve the purpose in either way

String to Hex Function

/**
 * CodeZone.in
 * Author: Dineshkumar
 * Contact : hi@codezone.in
 */
 function string2hex($string){
    $hex = '';
    for ($i=0; $i<strlen($string); $i++){
        $ord = ord($string[$i]);
        $hexCode = dechex($ord);
        $hex .= substr('0'.$hexCode, -2);
    }
    return strToUpper($hex);
}

Hex to String Function

/**
 * CodeZone.in
 * Author: Dineshkumar
 * Contact : hi@codezone.in
 */
 function hex2string($hex){
    $string='';
    for ($i=0; $i < strlen($hex)-1; $i+=2){
        $string .= chr(hexdec($hex[$i].$hex[$i+1]));
    }
    return $string;
}

Usage:

Include function in your PHP script and call them with required parameters to get your converted output.

Happy Coding….

Related posts

Rotate Text using CSS

While developing web pages we some time require to rotate text of images present...

Leave a Comment

Leave a Reply