Jump to content

Converting Cahracters To Hexadecimal Equivalent


s4surbhi2218

Recommended Posts

HI,

I want to write a code to convert each character of user enetered data to its equivalent four digit hexadecimal value.

eg : if user enters "Hi i am good"

convert H to its four digit hexadecimal

convert i to its four digit hexadecimal

convert blank to its four digit hexadecimal

and so on.

 

any suggestions would be great.

Many thanks.

Unfortunately ord () and char () only works for ASCII-characters, which means that if you introduce multi-byte characters to the mix Barand's solution will not work. In this case you should be using unpack () to convert the string to hexadecimal values.

If you really want to convert each character individually, then the following approach may be used:

/**
* Returns an array of the hexadecimal values for each character in the given string.
*
* @param string $string
* @param string[optional] $charset = 'UTF-8'
* @return array
*/
function hexify ($string, $charset = 'UTF-8') {
   $length = mb_strlen ($string, $charset);
   $retval = array ();
   for ($run = 0; $run < $length; $run++) {
       $temp = unpack ('H*', mb_substr ($string, $run, 1, $charset));
       $retval[] = $temp[1];
   }
   return $retval;
}

If it is imperative that the hexadecimal values returned are of at least 2 bytes long, then I'm sure you can sort it out sprintf (). ;) Do remember to take into account that quite a few UTF-8 characters can be more than just 2 bytes long though.

 

Edit: I should note that you can indeed use bin2hex () and hex2bin () for this purpose as well. As they do exactly the same as unpack () and pack () in this case. So while Silkfire's comment wasn't entirely accurate on the exact method needed, he was not wrong in his statement.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.