bin2hex()
The bin2hex() function is used to convert binary data into a hexadecimal string. The syntax of the bin2hex() function is as follows:
The PHP bin2hex() function converts a string of raw bytes into its hexadecimal representation. Each byte (8 bits) becomes exactly two hexadecimal digits, so the returned string is always twice as long as the input. Despite the name, the input is any binary-safe string — not a string of "0"/"1" characters — which makes bin2hex() the standard way to turn arbitrary binary data (image bytes, encryption keys, hashes) into a safe, printable ASCII form.
This page covers the syntax, a working example, how it differs from related functions, and the gotchas to watch for.
Syntax
bin2hex(string $string): stringIt takes a single parameter, $string — the binary data to encode — and returns a string of lowercase hexadecimal characters (0-9, a-f). The function has been available since PHP 4.0.5 and never returns false.
Basic example
Here the text "Hello, World!" is passed to bin2hex(), which encodes each character's byte value as two hex digits. The output is:
48656c6c6f2c20576f726c6421For instance the first character H has the byte value 0x48, e is 0x65, and so on — concatenating those pairs gives the result above.
Why use bin2hex()
The most common reason is to make binary data safe to print, log, store in a text column, or send in a URL. Raw bytes can contain non-printable or control characters; their hex form is pure ASCII.
<?php
// Generate 8 random bytes and show them as a hex token.
$bytes = random_bytes(8);
echo bin2hex($bytes); // e.g. "9f3a1c84e2b07d56" (16 hex chars)
?>A 16-character token is produced because 8 bytes map to 16 hex digits.
Reversing the conversion
Use hex2bin() to turn a hexadecimal string back into the original bytes. The two functions are exact inverses for any valid input:
<?php
$original = "PHP";
$hex = bin2hex($original); // "504850"
$restored = hex2bin($hex); // "PHP"
var_dump($original === $restored); // bool(true)
?>bin2hex() vs. dechex()
These are easy to confuse:
bin2hex()works on a string of bytes and encodes each byte as two hex digits.dechex()works on a single integer and returns its hex form without zero-padding.
<?php
echo bin2hex("A"); // "41" (the byte 0x41)
echo "\n";
echo dechex(65); // "41" (the integer 65)
echo "\n";
echo dechex(10); // "a" (no leading zero)
?>Gotchas
- Lowercase only.
bin2hex()always emits lowercase letters. If you need uppercase, applystrtoupper()to the result. - Length is doubled. The output length is always
2 * strlen($input); an empty string returns an empty string. - It is not encryption. Hex encoding is fully reversible and provides no security — it only changes the representation. For hashing use
md5()orsha1(), which already return hex strings.
Related functions
hex2bin()— the inverse operation.dechex()— convert a single integer to hexadecimal.ord()— get the byte value of a single character.strlen()— measure the byte length of a string.