hex2bin

(PHP >= 5.4.0)

hex2binПреобразует шестнадцатеричные данные в двоичные

Описание

string hex2bin ( string $data )

Декодирует строку данных из шестнадцатеричного представления

Предостережение

Эта функция НЕ конвертирует шестнадцатеричные числа в двоичные. Если нужно именно это, используйте функцию base_convert().

Список параметров

data

Шестнадцатеричное представление данных.

Возвращаемые значения

Возвращает двоичное представление данных, или FALSE в случае возникновения ошибки.

Ошибки

Если во входной шестнадцатеричной строке окажется нечетное число байт или она не является правильной шестнадцатеричной строкой, будет выдано предупреждение E_WARNING.

Список изменений

Версия Описание
5.5.1 Если входная строка не является правильной шестнадцатеричной строкой, то будет выброшено предупреждение.
5.4.4 Если строка имеет нечетную длину, выбрасывается предупреждение. В PHP 5.4.0 такая строка принималась, а последний байт просто обрезался.

Примеры

Пример #1 Пример использования hex2bin()

<?php
$hex 
hex2bin("6578616d706c65206865782064617461");
var_dump($hex);
?>

Результатом выполнения данного примера будет что-то подобное:

string(16) "пример hex данных"

Смотрите также

  • bin2hex() - Преобразует бинарные данные в шестнадцатеричное представление
  • unpack() - Распаковывает данные из бинарной строки

Коментарии

Автор:
The function hex2bin does not exist in PHP5.
You can use 'pack' instead :

$binary_string = pack("H*" , $hex_string);
2011-08-31 04:32:41
http://php5.kiev.ua/manual/ru/function.hex2bin.html
Автор:
The function pack("H*" , $hex_string); will not work as expected if $hex_string contains an odd number of hexadecimal digits.

For example:

<?php echo ord(pack("H*"'F')); ?>

will return 240 not 15. Use pack("H*", '0F'); instead.
2012-02-23 04:28:43
http://php5.kiev.ua/manual/ru/function.hex2bin.html
A way to convert hex strings in the form "0x123ABC" to integer is to use the function base_convert("0x123ABC", 16, 10)
2012-12-17 15:13:03
http://php5.kiev.ua/manual/ru/function.hex2bin.html
Автор:
For those who have php version prior to 5.4, i have a solution to convert hex to binary. It works for me in an encryption and decryption application.

<?php
       
function hextobin($hexstr)
    {
       
$n strlen($hexstr);
       
$sbin="";   
       
$i=0;
        while(
$i<$n)
        {       
           
$a =substr($hexstr,$i,2);           
           
$c pack("H*",$a);
            if (
$i==0){$sbin=$c;}
            else {
$sbin.=$c;}
           
$i+=2;
        }
        return 
$sbin;
    }
?>
2013-01-01 14:23:57
http://php5.kiev.ua/manual/ru/function.hex2bin.html
I modified the function by Johnson a bit so it can be used as a drop-in-replacement. You don't need to worry about upgrading php because when it is upgraded, it will use the build in function.

<?php
if ( !function_exists'hex2bin' ) ) {
    function 
hex2bin$str ) {
       
$sbin "";
       
$len strlen$str );
        for ( 
$i 0$i $len$i += ) {
           
$sbin .= pack"H*"substr$str$i) );
        }

        return 
$sbin;
    }
}
?>
2013-08-23 15:00:56
http://php5.kiev.ua/manual/ru/function.hex2bin.html
Автор:
A drop-in hex2bin emulator which behaves just like the the one in v5.5.1.

<?php
if (!function_exists('hex2bin')) {
    function 
hex2bin($data) {
        static 
$old;
        if (
$old === null) {
           
$old version_compare(PHP_VERSION'5.2''<');
        }
       
$isobj false;
        if (
is_scalar($data) || (($isobj is_object($data)) && method_exists($data'__toString'))) {
            if (
$isobj && $old) {
               
ob_start();
                echo 
$data;
               
$data ob_get_clean();
            }
            else {
               
$data = (string) $data;
            }
        }
        else {
           
trigger_error(__FUNCTION__.'() expects parameter 1 to be string, ' gettype($data) . ' given'E_USER_WARNING);
            return;
//null in this case
       
}
       
$len strlen($data);
        if (
$len 2) {
           
trigger_error(__FUNCTION__.'(): Hexadecimal input string must have an even length'E_USER_WARNING);
            return 
false;
        }
        if (
strspn($data'0123456789abcdefABCDEF') != $len) {
           
trigger_error(__FUNCTION__.'(): Input string must be hexadecimal string'E_USER_WARNING);
            return 
false;
        }
        return 
pack('H*'$data);
    }
}
?>
2013-10-16 07:41:35
http://php5.kiev.ua/manual/ru/function.hex2bin.html
Case of an incomplete hex string following function may help:
<?php
function make2validhex($data){
   
$data = (string) $data;
   
$len strlen($data);
    if(
$len 2) {
        return 
substr($data0$len -1);
    }
    return 
$data;
}
?>
test:
<?php
$string
="not complete"
echo 
$string;
echo 
PHP_EOL;
$hex bin2hex($string); //"6e6f7420636f6d706c657465"
echo $hex
echo 
PHP_EOL;
$deff substr ($hex0strlen($hex) -1);//"6e6f7420636f6d706c65746"
echo $deff;
echo 
PHP_EOL;
echo 
hex2bin(make2validhex($deff)); //"not complet"
echo PHP_EOL;
?>
2013-11-01 04:19:16
http://php5.kiev.ua/manual/ru/function.hex2bin.html
Автор:
Ran into an interesting case with hex2bin and php5.5.12 while upgrading from 5.3.3 -> 5.5.12

The previous code had redeclared the hex2bin function with the $binary_string = pack("H*" , $hex_string) trick. 

php5.5.12 would have none of that. The solution, albeit a hacky one, was doing a find an replace of hex2bin to 'hex3bin' for the whole site directory.
2014-06-12 01:14:01
http://php5.kiev.ua/manual/ru/function.hex2bin.html
$test = bin2hex('sample ...');
echo _hex2bin($test);

// another hex2bin replacement
function _hex2bin($result) {
    $out = '';
    for($c=0;$c<strlen($result);$c+=2) {
        $out .= chr(hexdec($result[$c].$result[$c+1]));
    } //end for
    return (string) $out;
}
2016-01-15 15:38:24
http://php5.kiev.ua/manual/ru/function.hex2bin.html
Автор:
replace

function Hex2Bin($data) {
    $BinData = "";
    for ($i=0;$i<strlen($data);$i+=2)
        $BinData .= chr( HexDec( substr($data,$i,2) ) );
    return $BinData;

With

function hextobin($hexstr) 
    { 
        $n = strlen($hexstr); 
        $sbin="";   
        $i=0; 
        while($i<$n) 
        {       
            $a =substr($hexstr,$i,2);           
            $c = pack("H*",$a); 
            if ($i==0){$sbin=$c;} 
            else {$sbin.=$c;} 
            $i+=2; 
        } 
        return $sbin;
2017-11-28 04:14:40
http://php5.kiev.ua/manual/ru/function.hex2bin.html
If you want to convert hex to GUID format (In my case, it was to convert GUID from MSSQL database) :

<?php
function hex2Guid($hex)
{
   
$hex = [
       
substr($hex08),
       
substr($hex84),
       
substr($hex124),
       
substr($hex164),
       
substr($hex20),
    ];

   
$order[0] = [67452301];
   
$order[1] = [2301];
   
$order[2] = [2301];
   
$order[3] = [0123];
   
$order[4] = [01234567891011];

   
$result "";

    for(
$num 0$num count($order); $num++)
    {
        for(
$i 0$i count($order[$num]); $i++)
        {
           
$result .= $hex[$num][$order[$num][$i]];
        }

        if(
$num != count($order) -1)
        {
           
$result .= "-";
        }
    }

    return 
strtoupper($result);
}

Example 
echo 
hex2Guid("64d3938b7008cd4bad5ffe56755d163f");

// return 8B93D364-0870-4BCD-AD5F-FE56755D163F
2019-12-03 16:30:32
http://php5.kiev.ua/manual/ru/function.hex2bin.html
if you want to convert a hex encoded string to a binary string without any notices/errors regardless of the input, use this function:

<?php

function hex2binary($str)
{
    return 
ctype_xdigit(strlen($str) % "" $str) ? hex2bin($str) : false;
}

hex2binary(""); // false
hex2binary("a"); // false
hex2binary("ab"); // binary-string

?>

if the return type is string, you have your binary-string. otherwise (bool) false.
2021-10-28 18:16:36
http://php5.kiev.ua/manual/ru/function.hex2bin.html
#error: 
hex2bin(): Hexadecimal input string must have an even length

For those who are facing the error above trying to convert hex to bin. you can pad your hex string with initial 0 before hex2bin.

function hexPad(string $hex_string)
    {
        $st_l = strlen($hex_string);
        return str_pad($hex_string, $st_l + ($st_l % 2), '0', STR_PAD_LEFT);
    }

hexPad('1bc') -> '01bc';

for usage hex2bin(hexPad('1bc'));
2022-08-21 14:54:27
http://php5.kiev.ua/manual/ru/function.hex2bin.html

    Поддержать сайт на родительском проекте КГБ