PHP hex2bin() Function

Beginner
⏱️ 7 min read
📚 Updated: Jul 2026
🎯 5 Examples
String Functions

What You’ll Learn

The hex2bin() function decodes a hexadecimal string back into raw binary bytes stored in a PHP string. It is the reverse of bin2hex()—not a tool for converting hex numbers to binary notation.

01

Hex Decode

Hex → raw bytes.

02

Even Length

Two digits per byte.

03

false on Fail

Invalid input check.

04

bin2hex Pair

Encode / decode.

05

Not base_convert

Data vs numbers.

06

Crypto / Debug

Keys, hashes, dumps.

Definition and Usage

In PHP, hex2bin() takes a string of hexadecimal characters and returns the original binary data. Each pair of hex digits represents one byte: 48 is the byte for ASCII H, 65 is e, and so on. The result is a normal PHP string holding raw bytes—which may or may not be readable text.

💡
Beginner Tip

Do not confuse hex2bin() with converting the number 255 to binary digits 11111111. For numeric radix conversion, use base_convert(). Use hex2bin() when you have hex-encoded byte data to decode.

📝 Syntax

The function accepts one hex-encoded string and returns decoded bytes or false:

PHP
string|false hex2bin(string $string)

Parameters

  • $string — hexadecimal representation of data. Valid characters: 0–9, a–f, A–F. Length must be even.

Return Value

Returns the binary string on success, or false if the input has odd length or contains invalid hex characters. PHP emits an E_WARNING on failure.

⚡ Quick Reference

Decode hex
hex2bin($hex)

Hex → bytes

Roundtrip
hex2bin(bin2hex($s))

Restore original

Safe check
$b = hex2bin($hex);
if ($b === false) { ... }

Handle failure

Numbers
base_convert($n, 16, 2)

Not hex2bin()

Examples Gallery

Run these examples in PHP 5.4+. Each demonstrates a common pattern beginners encounter with hex2bin().

📚 Getting Started

Decode a hex string that represents readable ASCII text.

Example 1 — Decode Hex to a Text String

Each pair of hex digits maps to one ASCII character in the decoded output.

PHP
<?php
$hexString  = "48656c6c6f2c20504850";
$binaryData = hex2bin($hexString);

echo "Hexadecimal: $hexString\n";
echo "Binary:      $binaryData\n";
?>

How It Works

48H, 65e, 6cl, and so on. The decoded string is plain text because every byte happens to be a printable ASCII character.

Example 2 — Roundtrip with bin2hex()

Encode with bin2hex(), decode with hex2bin(), and confirm the original is restored.

PHP
<?php
$original = "example hex data";
$hex      = bin2hex($original);
$restored = hex2bin($hex);

echo "Original: $original\n";
echo "Hex:      $hex\n";
echo "Restored: $restored\n";
echo "Match:    " . ($original === $restored ? "yes\n" : "no\n");
?>

How It Works

bin2hex() doubles the string length (one byte → two hex chars). hex2bin() reverses that exactly when the hex string is valid.

📈 Practical Patterns

Error handling, numeric conversion, and non-text byte data.

Example 3 — Odd Length Returns false

Always validate the result—invalid hex input fails instead of silently truncating.

PHP
<?php
$badHex = "48656c6c6f2";  // 11 chars — odd length
$result = hex2bin($badHex);

echo "Result: " . var_export($result, true) . "\n";
echo "Success: " . ($result !== false ? "yes\n" : "no\n");
?>

How It Works

Each byte needs two hex digits. An odd-length string cannot be decoded completely, so PHP returns false and raises a warning. Always compare with === false.

Example 4 — hex2bin() vs base_convert()

These functions solve different problems—a common beginner mistake is mixing them up.

PHP
<?php
// hex2bin: decode hex-encoded BYTE data
$bytes = hex2bin("ff00");           // 2 raw bytes
echo "hex2bin length: " . strlen($bytes) . "\n";

// base_convert: convert a NUMBER between bases
$digits = base_convert("ff", 16, 2); // "11111111"
echo "base_convert:   $digits\n";
?>

How It Works

hex2bin("ff00") produces two binary bytes (255 and 0). base_convert("ff", 16, 2) produces the string "11111111" representing the number 255 in binary notation—completely different semantics.

Example 5 — Decode Non-Text Binary Data

Not every decoded result is readable text—crypto keys, hashes, and file chunks are often stored as hex.

PHP
<?php
$hexKey = "deadbeef01234567";
$bytes  = hex2bin($hexKey);

echo "Hex:         $hexKey\n";
echo "Byte count:  " . strlen($bytes) . "\n";
echo "First byte:  " . ord($bytes[0]) . "\n";
echo "Last byte:   " . ord($bytes[strlen($bytes) - 1]) . "\n";
?>

How It Works

de → 222, ad → 173, and so on. Use ord() to inspect individual byte values when the decoded string is not human-readable text.

🚀 Common Use Cases

  • Decoding stored hex data — restore binary blobs saved as hex strings in databases or config files.
  • Cryptography workflows — convert hex-encoded keys, IVs, or ciphertext back to raw bytes.
  • Debugging — reverse a bin2hex() dump to inspect original byte content.
  • Protocol parsing — decode hex fields from network packets or serial data.
  • File handling — reconstruct binary file chunks transmitted as hex strings.

🧠 How hex2bin() Works

1

You pass a hex string

Input must contain only valid hex digits with an even character count.

Input
2

PHP validates and pairs digits

Each pair (e.g. 48) maps to one byte (72). Invalid or odd-length input returns false.

Transform
3

Binary string is built

Bytes are concatenated into a PHP string. Length equals half the hex string length.

Output
=

Raw byte string

Ready for crypto, file I/O, or further string processing.

📝 Notes

  • Available since PHP 5.4.0. On older versions use pack('H*', $hex).
  • Not the same as base_convert() for numeric radix conversion (see Example 4).
  • Input length must be even; odd length returns false with a warning.
  • Invalid characters (e.g. zz) also return false.
  • Always check for false before using the decoded result.

Conclusion

The hex2bin() function decodes hex-encoded byte data back into a PHP binary string. Pair it with bin2hex() for encoding, validate return values, and use base_convert() when you need numeric base conversion instead.

Whether you are restoring a debug dump, parsing a protocol field, or loading a crypto key, hex2bin() is the standard PHP tool for hex-to-bytes decoding.

💡 Best Practices

✅ Do

  • Check for false with strict comparison (=== false)
  • Use with bin2hex() for encode/decode roundtrips
  • Validate hex input length is even before calling
  • Use base_convert() for numeric base changes
  • Inspect non-text bytes with ord() and strlen()

❌ Don’t

  • Confuse hex2bin with hex-to-binary number conversion
  • Assume decoded output is always readable text
  • Ignore warnings on invalid hex input
  • Pass hex strings with spaces or 0x prefixes without stripping them
  • Display raw binary strings directly in HTML without encoding

Key Takeaways

Knowledge Unlocked

Five things to remember about hex2bin()

Use these points whenever you decode hex strings in PHP.

5
Core concepts
📝 02

Even Length

Two digits per byte.

Syntax
03

Returns false

On invalid input.

Errors
🔄 04

bin2hex Pair

Inverse encode.

Related
🔢 05

Not base_convert

Data vs numbers.

Distinction

❓ Frequently Asked Questions

hex2bin() decodes a hexadecimal string into its original binary form (returned as a PHP string of raw bytes). Each pair of hex digits becomes one byte—for example, "48656c6c6f" becomes the bytes that spell "Hello".
string|false hex2bin(string $string). Pass a hex-encoded string with an even number of characters (0–9, a–f, A–F). Returns the decoded binary string on success, or false on failure.
No. hex2bin() decodes hex-encoded byte data, not numeric radix conversion. To convert the number 255 from hex to binary digits, use base_convert('ff', 16, 2)—not hex2bin().
hex2bin() returns false and PHP emits an E_WARNING because each byte requires exactly two hex digits. An input like "414" (three characters) is invalid.
They are inverse operations. bin2hex() encodes raw bytes as hex; hex2bin() decodes hex back to bytes. Together they are useful for debugging, serialization, and crypto workflows.
hex2bin() is available in PHP 5.4.0 and later (including PHP 7 and 8). On PHP versions before 5.4, use pack('H*', $hex) as an alternative.

Explore More PHP String Functions

Continue with html_entity_decode(), htmlspecialchars(), and the rest of the string function reference.

Next: html_entity_decode() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful