The function pack("H*" , $hex_string); will not work as expected if $hex_string contains an odd number of hexadecimal digits.
For example:
<?php echo ord(pack("H*", 'F')); ?>
will return 240 not 15. Use pack("H*", '0F'); instead.
hex2bin
(PHP >= 5.4.0)
hex2bin — Decodes a hexadecimally encoded binary string
Description
string hex2bin
( string
$data
)Decodes a hexadecimally encoded binary string.
Caution
This function does NOT convert a hexadecimal number to a binary number. This can be done using the base_convert() function.
Parameters
-
data -
Hexadecimal representation of data.
Return Values
Returns the binary representation of the given data or FALSE on failure.
Errors/Exceptions
If the hexadecimal input string is of odd length an E_WARNING
level error is thrown.
Changelog
| Version | Description |
|---|---|
| PHP 5.4.1 | A warning is thrown if the input string is of odd length. In PHP 5.4.0 the string was silently accepted, but the last byte was truncated. |
Examples
Example #1 hex2bin() example
<?php
$hex = hex2bin("6578616d706c65206865782064617461");
var_dump($hex);
?>
The above example will output something similar to:
string(16) "example hex data"
Anonymous
22-Feb-2012 08:28
Anonymous
30-Aug-2011 08:32
The function hex2bin does not exist in PHP5.
You can use 'pack' instead :
$binary_string = pack("H*" , $hex_string);
