Current Location: Home> Latest Articles> PHP hex2bin() Function Guide: Hexadecimal to Binary Conversion

PHP hex2bin() Function Guide: Hexadecimal to Binary Conversion

gitbox 2025-06-25

1. Introduction

The hex2bin() function in PHP is a very useful built-in function that converts a hexadecimal string into binary data. It works by converting every two hexadecimal characters (e.g., "41") into one byte (i.e., "A"), and then concatenating all the bytes into a binary string, which is returned.

2. Syntax

The basic syntax of the hex2bin() function is as follows:


string hex2bin(string $data)

The parameter $data is required and represents the hexadecimal string to be converted.

3. Example

Here is a simple example demonstrating how to use the hex2bin() function to convert a hexadecimal string into binary data:


<?php
    $str = "48656c6c6f20576f726c64";
    $bin = hex2bin($str);
    echo $bin;
?>

When you run the above code, the output will be:

<span class="fun">Hello World</span>

4. Considerations

There are a few things to keep in mind when using hex2bin(). First, ensure that the length of the hexadecimal string is even. If the string has an odd number of characters, it will result in a parsing error and fail to convert correctly.

5. Conclusion

The hex2bin() function is highly useful when dealing with hexadecimal data, especially when parsing binary files or network communication packets. Mastering its usage can help you handle various binary data-related tasks more effectively.