在php中从ascii转换为hex

时间:2014-07-04 13:16:30

标签: php hex ascii

我试图在PHP中将ASCII转换为HEX,但对一些可用的在线工具获得了不同的结果。我知道我要查找的结果,因此the online tool's结果似乎是正确的,我的代码不正确,但我无法解决原因。

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

我的剧本:

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

错误在哪里?

3 个答案:

答案 0 :(得分:8)

使用:

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;
}

结果:

ascii to hex

答案 1 :(得分:1)

试试这个:

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

答案 2 :(得分:0)

感谢 Patrick Maciel 的好回答。 现在,如果使用 PHP 7.4,可能会出现错误消息“不再支持带花括号的数组和字符串偏移访问语法”。用“[”和“]”代替“{”和“}”可以解决问题。

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