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?

Gottlieb Notschnabel
  • 9,408
  • 18
  • 74
  • 116
SamMaj
  • 358
  • 1
  • 5
  • 14

3 Answers3

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

Patrick Maciel
  • 4,874
  • 8
  • 40
  • 80
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