Content · Programming · PHP

PHP hex2bin() Function: Usage and Examples

Understand PHP hex2bin() with three examples, return behavior, important pitfalls, and related operations.

1 views Published Oct 16, 2026 Updated Oct 16, 2026

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

ApproachDifference
hex2bin()Decodes a hexadecimal digit string into binary bytes.
Related operationbin2hex() encodes bytes into hex text; hex2bin() decodes the text.

Common Beginner Mistakes

MistakeCorrect Approach
Ignoring the function-specific limitationThe input must have an even number of valid hexadecimal digits. Encoding is not encryption.
Confusing this function with a related operationbin2hex() 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.

Share this resourceSend this page to someone who may find it useful.