3

I'm trying to convert from ASCII to HEX in PHP but get a different result to some of the online tools that are available. I know the result I'm looking for so the online tool's result appear to be correct and my code incorrect but I can't work out why.

String:         2Ffbj?DoyXOU
Correct output: 32 46 66 62 6a 3f 44 6f 79 58 4f 55 (from linked site above)
My output:      32 46 66 62 6a 3f 44 6f 79 58 4f 75

My script:

echo bin2hex(utf8_decode("2Ffbj?DoyXOU"));

Where is the fault?

3 Answers 3

11

Use that:

function ascii2hex($ascii) {
  $hex = '';
  for ($i = 0; $i < strlen($ascii); $i++) {
    $byte = strtoupper(dechex(ord($ascii{$i})));
    $byte = str_repeat('0', 2 - strlen($byte)).$byte;
    $hex.=$byte." ";
  }
  return $hex;
}

The result:

ascii to hex

3
  • 2
    Can you explain why the OPs way doesn't return proper result? Jul 4, 2014 at 13:21
  • 1
    I was just curious why this algorithm may work while bin2hex() won't return proper result. Jul 4, 2014 at 22:22
  • @GottliebNotschnabel it is not working because bin2hex (and) hex2bin are kind of not what you expect. Bin in php in this case is a string of 0's and 1's eg.: "010110101" not binary data.
    – Kladskull
    Dec 22, 2021 at 22:24
1

Try this:

function ascii2hex($arg){
   return implode(" ",array_map(fn($x) => sprintf("%02s",strtoupper(dechex(ord($x)))),str_split($arg)));
}
0

Thanks Patrick Maciel for the good answer. Now if use PHP 7.4, there maybe an error message "Array and string offset access syntax with curly braces is no longer supported". Using "[" and "]" to replace "{" and "}" can solve the problem.

Reference: Array and string offset access syntax with curly braces is deprecated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.