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

Sign up to request clarification or add additional context in comments.

3 Comments

Can you explain why the OPs way doesn't return proper result?
I was just curious why this algorithm may work while bin2hex() won't return proper result.
@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.
1

Try this:

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

Comments

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.