PHP bin2hex() Function

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

What You’ll Learn

The bin2hex() function converts a string of raw bytes into a hexadecimal text representation. Each byte becomes two hex digits—ideal for displaying hashes, debugging binary data, or storing non-text bytes in a readable format.

01

Binary to Hex

Bytes become hex pairs.

02

One Parameter

Pass any byte string.

03

Lowercase Output

Uses a–f, not A–F.

04

hex2bin()

Reverse the conversion.

05

Hash Display

Show digests as hex text.

06

vs dechex()

Strings vs integers.

Definition and Usage

In PHP, strings are binary-safe—they can hold any sequence of bytes, not just readable text. bin2hex() takes such a string and returns a hexadecimal encoding where every byte is written as two characters. For example, the text "Hello, PHP!" becomes 48656c6c6f2c2050485021.

💡
Beginner Tip

Think of bin2hex() as a viewer for raw bytes. It does not change the meaning of your data—it re-expresses each byte as two hex digits so humans can read and copy it. To go back, use hex2bin().

📝 Syntax

The bin2hex() function accepts one string parameter:

PHP
string bin2hex(string $string)

Parameters

  • $string — the binary data to encode. In PHP, ordinary strings already hold raw bytes, so text like "ABC" works perfectly.

Return Value

Returns a lowercase hexadecimal string. The output length is always twice the input byte length. The original string is not modified.

⚡ Quick Reference

Input (bytes)Hex Output
"A" (byte 65)41
"Hello, PHP!"48656c6c6f2c2050485021
"\x00\xFF"00ff
"" (empty)""
"PHP" (3 bytes)504850 (6 chars)
Basic
bin2hex($data)

Encode bytes to hex

Reverse
hex2bin($hex)

Decode hex to bytes

Length
strlen($hex) === 2 * strlen($bin)

Output is 2× input

Compare
dechex(255) // "ff"

For integers only

Examples Gallery

Run these examples in any PHP 7+ environment. Each one demonstrates a common pattern beginners encounter with bin2hex().

📚 Getting Started

Convert a plain text string into its hexadecimal representation.

Example 1 — Convert Text to Hexadecimal

The classic beginner example: turn readable text into a continuous hex string, one byte at a time.

PHP
<?php
$binaryData = "Hello, PHP!";
$hexString  = bin2hex($binaryData);

echo "Binary Data: $binaryData\n";
echo "Hex String:  $hexString\n";
echo "Input length:  " . strlen($binaryData) . " bytes\n";
echo "Output length: " . strlen($hexString) . " chars\n";
?>

How It Works

  • H (byte 72) → 48, e (101) → 65, and so on.
  • 11 input bytes produce 22 hex characters—always double the byte count.
  • Output uses lowercase letters af.

Example 2 — Encoding Raw Byte Values

PHP strings can hold any byte value, including non-printable characters. bin2hex() makes them visible.

PHP
<?php
$bytes = "\x00\x0A\xFF\x41";  // NUL, newline, 255, 'A'
$hex   = bin2hex($bytes);

echo "Hex: $hex\n";
?>

How It Works

Byte 0 becomes 00, newline (10) becomes 0a, 255 becomes ff, and A becomes 41. This is especially useful when debugging binary protocols or file headers.

📈 Practical Patterns

Real-world scenarios where hex encoding appears in PHP projects.

Example 3 — Round-Trip with hex2bin()

Encode with bin2hex(), then decode back with hex2bin() to recover the original bytes.

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

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

How It Works

hex2bin() is the inverse of bin2hex(). It returns false if the hex string has an odd length or contains non-hex characters—always validate the result.

Example 4 — Displaying a Hash as Hex

Hash functions like hash() with raw output return binary data. Use bin2hex() to show a familiar hex digest string.

PHP
<?php
$password = "mySecret123";

// hash() with true returns raw 20-byte SHA-1 binary
$rawHash = hash("sha1", $password, true);
$hexHash = bin2hex($rawHash);

// hash() without true already returns hex — compare lengths
$directHex = hash("sha1", $password);

echo "Raw hash length:  " . strlen($rawHash) . " bytes\n";
echo "bin2hex output:   $hexHash\n";
echo "hash() default:   $directHex\n";
echo "Same result:      " . ($hexHash === $directHex ? "yes\n" : "no\n");
?>

How It Works

When a function returns raw binary (the third argument true in hash()), bin2hex() converts it to the same hex string PHP would produce by default. This pattern appears in cryptography and checksum libraries.

Example 5 — bin2hex() vs dechex()

Understand when to encode a byte string versus converting a single integer to hex.

PHP
<?php
$number = 255;
$text   = "\xFF";  // single byte with value 255

echo "dechex(255):     " . dechex($number) . "\n";
echo "bin2hex(\"\\xFF\"): " . bin2hex($text) . "\n";
echo "bin2hex(\"255\"):   " . bin2hex("255") . "\n";
?>

How It Works

  • dechex(255) converts the integer 255 to "ff".
  • bin2hex("\xFF") encodes the byte 255 as "ff".
  • bin2hex("255") encodes the three ASCII characters 2, 5, 5 as 323535—completely different.

🚀 Common Use Cases

  • Hash and checksum display — show SHA, MD5, or HMAC digests as readable hex strings.
  • Debugging binary data — inspect file contents, network packets, or API responses byte by byte.
  • UUID and token formatting — convert raw binary identifiers to hex for logs or URLs.
  • Data serialization — store binary blobs in text-only formats like JSON or CSV.
  • Learning encoding — understand how bytes map to hexadecimal before exploring Base64 or other encodings.

🧠 How bin2hex() Works

1

PHP reads the byte string

You pass any string—text, raw bytes, or hash output. PHP treats it as a sequence of bytes.

Input
2

Each byte becomes two hex digits

PHP converts every byte (0–255) into a pair of lowercase hex characters, from 00 to ff.

Transform
3

Hex string is returned

The result is twice as long as the input. The original string stays unchanged.

Output
=

Human-readable hex

Ready for display, logging, storage in text formats, or decoding with hex2bin().

📝 Notes

  • Output is always lowercase. Use strtoupper() if you need uppercase hex.
  • Output length = 2 × input byte length. A 16-byte UUID raw string produces 32 hex characters.
  • hex2bin() reverses the process but returns false on invalid input.
  • For large files, consider reading in chunks rather than loading entire files into memory before encoding.
  • bin2hex() is encoding, not encryption—hex strings can be decoded by anyone.

Conclusion

The bin2hex() function is a simple, reliable way to represent binary data as hexadecimal text in PHP. Whether you are displaying a hash digest, inspecting raw bytes, or preparing data for a text-based format, it converts every byte into two readable hex characters.

Pair it with hex2bin() for round-trip encoding, and remember the distinction from dechex()—which works on integers, not byte strings.

💡 Best Practices

✅ Do

  • Use bin2hex() to display raw hash or binary output
  • Validate hex2bin() results—check for false
  • Use hash('algo', $data) directly when you only need hex hashes
  • Remember output is lowercase by default
  • Account for doubled string length in storage or UI layout

❌ Don’t

  • Confuse bin2hex("255") with dechex(255)
  • Treat hex encoding as security or encryption
  • Assume hex2bin() accepts odd-length strings
  • Load huge binary files entirely into memory without need
  • Use bin2hex() when Base64 is the required format for your API

Key Takeaways

Knowledge Unlocked

Five things to remember about bin2hex()

Use these points whenever you work with binary data in PHP.

5
Core concepts
🔄 02

hex2bin()

Decodes hex back.

Companion
🛠 03

2× Length

Output doubles input.

Rule
🔒 04

Hash Display

Raw digest to text.

Use case
05

vs dechex()

Strings vs integers.

Compare

❓ Frequently Asked Questions

bin2hex() converts a string of binary data into its hexadecimal representation. Each byte in the input becomes two lowercase hex characters (0–9, a–f) in the output.
string bin2hex(string $string). You pass a string (PHP strings hold raw bytes) and receive a hex-encoded string. The original is not modified.
Each byte (8 bits) is represented by exactly two hexadecimal digits. For example, the byte 255 becomes "ff" and the letter A (byte 65) becomes "41".
Use hex2bin(), the companion function. It decodes a hex string back into its original binary form. hex2bin() returns false if the input contains invalid hex characters or has an odd length.
bin2hex() converts an arbitrary string of bytes to hex. dechex() converts a single integer to its hexadecimal representation. Use bin2hex() for binary data and dechex() for numeric values.
It returns an empty string. No error is raised.

Explore More PHP String Functions

Continue with chop(), chr(), and the rest of the string function reference.

Next: chop() →

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