Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท String Functions

PHP bin2hex() and hex2bin() functions

Reference for PHP bin2hex() and hex2bin(): convert bytes to hexadecimal text and back, why the output is twice as long, odd-length warnings and token generation.

bin2hex() converts a string of bytes into its hexadecimal representation: each byte becomes two characters from 0-9a-f. hex2bin() does the opposite and turns a hex string back into the original bytes. They are the simplest way to display or store binary data, such as hashes, random tokens and encryption keys, in a form that is safe for URLs, logs and text columns.

Hex is twice the size of the original data, but it is easy to read and has no special characters. For more compact text, see base64_encode().

PHP
<?php
echo bin2hex("PHP");        // 504850
echo hex2bin("504850");     // PHP

Try it

PHP Bytes to hex and back

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Invalid input and tokens

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
bin2hex(string $string): string
hex2bin(string $string): string|false
Name Description
$string For bin2hex(): any string of bytes. For hex2bin(): a string of hexadecimal digits, upper or lower case, with an even length.

Return value: bin2hex() returns a lower-case hex string twice as long as the input. hex2bin() returns the binary string, or false if the input has an odd length or contains a character that is not a hex digit. In both failure cases PHP also emits a warning.

Usage notes

  • Lower-case output. bin2hex() always produces a-f. Use strtoupper() if you need capitals.
  • Even length required. hex2bin("abc") fails with a warning. Pad a leading zero yourself if the digits came from a number.
  • Not a number converter. bin2hex("255") converts the three characters 2, 5, 5 (bytes 0x32 0x35 0x35), giving 323535. To turn the integer 255 into ff use dechex(255); to go back use hexdec().
  • Warnings, not exceptions. Always compare hex2bin()'s result with === false, or validate input first with ctype_xdigit().
  • Random tokens. bin2hex(random_bytes($n)) is a standard way to create a secure token of 2 * $n characters. Do not build tokens from rand() or uniqid().
  • Hashes. Many hash functions can return raw bytes with a true argument (md5($s, true), hash('sha256', $s, true)); bin2hex() gives the usual hex form.
  • Multibyte text. The output shows the real UTF-8 bytes, so bin2hex("โ‚ฌ") is e282ac, which is useful when debugging encodings.