W3docs

hex2bin()

The hex2bin() function is used to convert a hexadecimal string to its binary representation. The syntax of the hex2bin() function is as follows:

The hex2bin() function is used to convert a hexadecimal string to its binary representation. Available since PHP 5.4, its syntax is as follows:

Syntax

string hex2bin ( string $hex_string )

The function takes one required parameter, $hex_string, which is the hexadecimal string to convert.

Here is an example of how to use the hex2bin() function:

Example of PHP hex2bin()

<?php
$hex_string = "48656c6c6f20576f726c64";
$binary_string = hex2bin($hex_string);
echo $binary_string;
?>

In this example, we have a string variable $hex_string containing a hexadecimal string. We use the hex2bin() function to convert the hexadecimal string to its binary representation.

The output of this code will be:

Hello World

As you can see, the hex2bin() function has converted the hexadecimal string to its binary representation, which is the string "Hello World".

The hex2bin() function returns false if the input string contains invalid hexadecimal characters. To handle this situation gracefully and avoid warnings, you can validate the input first using ctype_xdigit():

How to use hex2bin()?

<?php
$invalid_hex_string = "48656c6c6f20576f726c4";

if (!ctype_xdigit($invalid_hex_string)) {
  echo "Invalid input: $invalid_hex_string";
} else {
  $binary_string = hex2bin($invalid_hex_string);
  echo $binary_string;
}
?>

In this example, we have a string variable $invalid_hex_string containing an invalid hexadecimal string. We use ctype_xdigit() to check if the string contains only valid hexadecimal characters before calling hex2bin(). If the validation fails, we display an error message. Otherwise, we safely convert the string to binary.

The hex2bin() function is a useful tool for converting a hexadecimal string to its binary representation. It can help make your code more versatile and flexible when working with binary data, such as encrypted data or binary files. By mastering this function, you can become a more proficient PHP developer.

We hope this article has been helpful in understanding the hex2bin() function in PHP.

Practice

Practice

What does the hex2bin() function in PHP do?