Use hex2bin() when you need to decodes a hexadecimal digit string into binary bytes in a PHP application. The examples below show the actual operation and its limitations.
What Is hex2bin() in PHP?
Decodes a hexadecimal digit string into binary bytes. The exact signature supported by your installation depends on its PHP version and enabled extensions.
Its syntax is:
hex2bin(string $string): string|false
Parameters and return value: The parameter types, optional arguments, references, and return type are shown in the signature above. Optional parameters are marked with an ellipsis in this reference signature.
Example 1: Basic Usage
<?php
echo hex2bin("4869");
Output:
Hi
Example 2: Different Input or Behavior
<?php
echo bin2hex(hex2bin("00ff"));
Output:
00ff
Practical Example: Applying the Function
<?php
$storedHex = "414243"; if (ctype_xdigit($storedHex) && strlen($storedHex) % 2 === 0) echo hex2bin($storedHex);
Output:
ABC
Important Behavior and Edge Cases
The input must have an even number of valid hexadecimal digits. Encoding is not encryption.
Comparison With Related Functions
| Approach | Difference |
|---|---|
hex2bin() | Decodes a hexadecimal digit string into binary bytes. |
| Related operation | bin2hex() encodes bytes into hex text; hex2bin() decodes the text. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring the function-specific limitation | The input must have an even number of valid hexadecimal digits. Encoding is not encryption. |
| Confusing this function with a related operation | bin2hex() encodes bytes into hex text; hex2bin() decodes the text. |
Key Takeaways
- Decodes a hexadecimal digit string into binary bytes.
- The input must have an even number of valid hexadecimal digits. Encoding is not encryption.
- bin2hex() encodes bytes into hex text; hex2bin() decodes the text.
Use hex2bin() for the specific operation demonstrated above. Check its prerequisites and handle failure conditions before using it with production data.