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.

Link to comment
Share on other sites

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.

Edited by Christian F.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.