Developer Guide

PHP hex2bin(): Convert Hex to Bytes the Right Way

hex2bin() turns a hexadecimal digit string into raw bytes. It is the inverse of bin2hex(). Most “hex to string” tasks in PHP are hex2bin plus an optional character-encoding step.

Broader guide: PHP hex to string. Online tool: Hex to String.

Signature and basic use

<?php
$hex = '48656c6c6f';
$bin = hex2bin($hex);
echo $bin;                 // Hello
echo bin2hex($bin);        // 48656c6c6f

Input must be an even-length string of hex digits. Spaces are not allowed — strip them first.

<?php
$hex = preg_replace('/\s+/', '', '48 65 6c 6c 6f');
echo hex2bin($hex);

Error behavior

<?php
function requireHexBytes(string $hex): string
{
    $hex = preg_replace('/\s+/', '', $hex) ?? '';
    if ($hex === '' || strlen($hex) % 2 !== 0 || !ctype_xdigit($hex)) {
        throw new InvalidArgumentException('invalid hex');
    }
    return hex2bin($hex);
}

UTF-8 and other encodings

hex2bin does not know about UTF-8. It only rebuilds bytes. If those bytes are UTF-8 text, the PHP string is already usable as UTF-8 text. If they are GBK (or anything else), convert explicitly:

<?php
$bytes = hex2bin($gbkHex);
$utf8 = mb_convert_encoding($bytes, 'UTF-8', 'GBK');

pack('H*') vs hex2bin

<?php
echo pack('H*', '48656c6c6f'); // Hello

Similar result for typical hex strings. Prefer hex2bin when the only goal is hex decoding; use pack when mixing multiple binary formats. See pack() guide.

Storage note

Hex is great for logs and debugging. For database persistence of binary payloads, store binary/BLOB (or base64 if you must stay in text columns). Storing everything as hex doubles size and slows indexes.

Also read: string to hex · hex encoding overview.