Link to home
Start Free TrialLog in
Avatar of skij
skijFlag for Canada

asked on

PHP: Convert Hexadecimal String to a-z and A-Z and 0-1

Using PHP, how can I convert this:
3eb24feacab0c1f1054a5133b5000b28

into a shorter string that uses numbers and lower case and uppercase letters?
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Uhh, what would the expected output be?  Does each pair of characters (eg: 3e, b2, etc) represent something you want in the output?  What would you want to get from "00" here?
Use this function:

function hextostr($hex)
{
    $str='';

    for ($i = 0; $i < strlen($hex) - 1; $i += 2)
    {
        $str .= chr(hexdec($hex[$i].$hex[$i+1]));
    }

    return $str;
}

This hex string = "48654c4c6f20576f526c4421"
... would return = "HeLLo WoRlD!"

Resources and citations from here:

http://www.stringfunction.com/hex-string.html  <- online conversion test tool
http://www.stringfunction.com/php/hexdec-hex-string.html   <- tutorial
( your hex string ....  

 "3eb24feacab0c1f1054a5133b5000b28" = ">²OêÊ°ÁñJQ3µ ("

)
SOLUTION
Avatar of ChloesDad
ChloesDad
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of skij

ASKER

The output should only contain letters a-z and A-Z and the numbers 0-9.  No spaces or other characters such as > or ê or Á should be included in the output.
hello skij, , Do u need a "filtering" method for HEX input, as if you have a HEX string like -
          "3eb24feacab0c1f1054a5133b5000b28"
you require an output to be -
         "OJQ3"
? ? ?
There's a filter added:

function hextostr($hex)
{
    $str='';
    $chars = 'abcdefghijklmnopqrstuwvxyzABCDEFGHIJKLMNOPQRSTUWVXYZ0123456789';

    for($i = 0; $i < strlen($hex) - 1; $i += 2)
    {
        $alpha = chr(hexdec($hex[$i].$hex[$i+1]));

        if(strpos($chars, $alpha) !== FALSE)
        {
            $str .=  $alpha;
        }
    }

    return $str;
}

Open in new window

mine is more mathematical -

function getAlpha($str) {
$ary = str_split($str,2);
$str = '';
for ($i=0; $i < count($ary); ++$i) {
   $dec = hexdec($ary[$i]);
   if ((($dec > 47) && ($dec < 58)) || 
      (($dec > 64) && ($dec < 91)) || 
      (($dec > 96) && ($dec < 123))) 
      $str .= chr($dec);
   }
return $str;
}



$hex = '3eb24feacab0c1f1054a5133b5000b28';
$hex = getAlpha($hex);
echo 'HEX Filter is= ',$hex;

Open in new window

change:

for ($i=0; $i < count($ary); ++$i)

Open in new window


to

foreach($ary as $hexval)

Open in new window


Then:

if ((($dec > 47) && ($dec < 58)) || 
      (($dec > 64) && ($dec < 91)) || 
      (($dec > 96) && ($dec < 123))) 

Open in new window


To:

switch(TRUE)
    case [...]

Open in new window


http://php.net/manual/en/control-structures.switch.php

... and it is competitive, but still slower. I like the flow otherwise.
I was going to try to write a hex-to-character example for this question, but as I re-read the answers I think Frank Pennock has mostly answered your question.  And at the same time I think there may be a subtext or back-story to the question that we do not have in evidence here.  The real question may be "why do you want to do this?" Maybe you can tell us a little more about the nature of the application?  We do not need technical details - just the "50,000 foot" view.  Where does this data come from?  What do you want to do with it and why?  Where are you going to view or store the results of this conversion?  If you can tell us the essential things about the application we may be able to suggest good ways to approach the problem.
comment to Frank Pennock, Thanks for the suggestions, I implemented your code changes as -
function getAlpha2($str) {
$ary = str_split($str,2);
$str = '';
foreach($ary as $hexval) {
  $dec = hexdec($hexval);
  switch (true) {
    case (($dec > 47) && ($dec < 58)):
    case (($dec > 64) && ($dec < 91)):
    case (($dec > 96) && ($dec < 123)): $str .= chr($dec);
  }
}
return $str;
}

Open in new window

and it seems to work as well as my first version on some different HEX strings.
I much prefer to use the direct code handling in for() loops, other than the representative symbolic in  foreach() loops, as the foreach() needs to go to the trouble of making a Copy of the value in the array, although you can get around this with the & -
      foreach($ary as &$hexval)
but I can have more control in for() loops and go in the reverse direction or start at a place other than the first.

The switch() was not something I thought about here, and I like your thinking on that point.
I like to cooperate coding in building web apps, but it is a rare thing here at EE, at least that's my view.
Frank, you seem like a knowledgeable coder in PHP and JS, Glad you are now among the code heads here on EE. welcome to the stumble bumble, of EE!
 foreach($ary as &$hexval)

Open in new window



... regardless of the reference, you still need to unset $hexval after the loop.

I basically use a switch() case every time I'm using more than 1 OR statement, or more than 2 elseif. It's just cleaner.

- Thanks for your compliments! I'm glad to be here. It's just rare to find people who collaborate without being offput or offended. I like how you take the time to learn what happens behind the scenes of the code and not just willy nilly use poor methods which slow things down.
Frank, I do see many many code blocks shown here in questions, that are from sources years, maybe even a decade old, that use poor judgement in picking the operations for work, that the PHP coders have inherited over the years, as copy and paste examples, mostly due to the very short operational and how to use , explanations in the PHP official manual, , but if I read all of the user comments below the manual explanations, I see that there can be much more to use and have better code work. With the very fast transition now, from click browser, to touch app Mobil, many PHP web developers seem to be two and three steps behind in the knowledge required for responsive interactive touch phone web sites, resulting in  (as you put it) "willy nilly poor methods which slow things down".
Avatar of skij

ASKER

Thank you all for your ideas.  I am looking for something that can be converted back and forth.  No data should be destroyed in the conversion.  The closest thing I can think of would be to base64_encode() however that would include characters other than letters and numbers.
Are you wanting to produce the hexadecimal representations of a string of characters, then reproduce the characters from the hex string?  Maybe something like what they do here?
https://www.branah.com/ascii-converter

PHP base64_encode() and base64_decode() are certainly reversible.  They can be paired with some kind of filter function to remove the non-alphanumeric characters.  But I'm still looking for the "why" in this question.  If we understand that, we can probably show you a best-practices solution instead of just guessing about data conversions.  Maybe if you can show us some of the expected "real world" input it would help us give you a good answer.
You're talking about using RSA encryption then. I didn't know you wanted to actually create object level encryption. RSA is the best alphanumeric encryption you'll find, and the phpseclib library in PHP can work directly with it. Have a look here:

http://phpseclib.sourceforge.net/
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Yeah, I'm confused as to what exactly needs to be done, because the original question said take hex and convert it to a string. That's what was done and now it doesn't seem to answer the question.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial