略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: hex2bin

2024-11-15

hex2bin

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

hex2bin转换十六进制字符串为二进制字符串

说明

hex2bin(string $data): string

转换十六进制字符串为二进制字符串。

警告

这个函数不是 转换十六进制数字为二进制数字。这种转换可以使用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) "example hex data"

参见

  • bin2hex() - 函数把包含数据的二进制字符串转换为十六进制值
  • unpack() - Unpack data from binary string
add a noteadd a note

User Contributed Notes 12 notes

up
6
nino at re-gister dot com
7 months ago
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) % 2 ? "" : $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.
up
37
Anonymous
10 years ago
The function hex2bin does not exist in PHP5.
You can use 'pack' instead :

$binary_string = pack("H*" , $hex_string);
up
4
jannik [dot] zappe [at] udo [dot] edu
8 years ago
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 += 2 ) {
           
$sbin .= pack( "H*", substr( $str, $i, 2 ) );
        }

        return
$sbin;
    }
}
?>
up
2
Anonymous
10 years ago
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.
up
-2
Johnson
9 years ago
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;
    }
?>
up
-1
omer dot lakraa at hotmail dot fr
2 years ago
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($hex, 0, 8),
       
substr($hex, 8, 4),
       
substr($hex, 12, 4),
       
substr($hex, 16, 4),
       
substr($hex, 20),
    ];

   
$order[0] = [6, 7, 4, 5, 2, 3, 0, 1];
   
$order[1] = [2, 3, 0, 1];
   
$order[2] = [2, 3, 0, 1];
   
$order[3] = [0, 1, 2, 3];
   
$order[4] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];

   
$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
up
-2
walf
8 years ago
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);
    }
}
?>
up
-2
carschrotter at gmail dot com
8 years ago
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($data, 0, $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 ($hex, 0, strlen($hex) -1);//"6e6f7420636f6d706c65746"
echo $deff;
echo
PHP_EOL;
echo
hex2bin(make2validhex($deff)); //"not complet"
echo PHP_EOL;
?>
up
-3
iradu at unix-world dot org
6 years ago
$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;
}
up
-5
jarismar dot php at gmail dot com
9 years ago
A way to convert hex strings in the form "0x123ABC" to integer is to use the function base_convert("0x123ABC", 16, 10)
up
-3
JLovrek
4 years ago
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;
up
-25
EM
8 years ago
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.

官方地址:https://www.php.net/manual/en/function.hex2bin.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3