How can I get a hex dump of a string in PHP?

后端 未结 6 1146
陌清茗
陌清茗 2020-11-22 07:50

I\'m investigating encodings in PHP5. Is there some way to get a raw hex dump of a string? i.e. a hex representation of each of the bytes (not characters) in a string?

6条回答
  •  一生所求
    2020-11-22 08:17

    "Functional" version:

    $s = "\x04\x00\xa0\x00";
    echo implode(' ', array_map(function($char) {
        # return sprintf('%02s', $char);
        return str_pad($char, 2, '0', STR_PAD_LEFT);
    }, array_map('dechex', unpack('C*', $s))));
    

    Borrowing from Ionuț G. Stan's comment, the last line might be as follows:

    }, array_map('dechex', array_map('ord', str_split($s)))));
    

提交回复
热议问题