Search for:


PHP hex2bin Function

The PHP hex2bin() function is a built-in function that converts a hexadecimal string to its corresponding binary representation. It takes a string of hexadecimal digits as input and returns the binary data represented by that string.

Here’s an explanation of the hex2bin() function and its usage:

The hex2bin() function was introduced in PHP 5.4.0 and is commonly used when dealing with binary data manipulation, such as encoding and decoding binary files or working with cryptographic functions.


hex2bin(string $hex_string): string|false


  • $hex_string: A string containing a valid hexadecimal representation.

Return Value:

  • The binary representation of the hexadecimal string, or false on failure.

Example usage:

$hex_string = '48656c6c6f20576f726c64';
$binary_data = hex2bin($hex_string);

echo $binary_data;


Hello World

In this example, the $hex_string variable contains the hexadecimal representation of the string “Hello World.” The hex2bin() function is called with this string as input, and the resulting binary data is stored in the $binary_data variable. Finally, the binary data is echoed, resulting in the output “Hello World.”

It’s important to note that the input string must have an even number of characters, representing complete bytes. If the input string has an odd number of characters, the last character will be ignored.

If the input string contains invalid hexadecimal characters, hex2bin() will return false. Additionally, in PHP versions prior to 7.4.0, an E_WARNING level error would be generated. Starting from PHP 7.4.0, a false return value is used instead, and the error is suppressed.

Overall, the hex2bin() function is a useful tool when working with binary data in PHP, allowing you to convert hexadecimal strings to binary representations for further processing or manipulation.