字符串函数
在线手册:中文 英文
PHP手册

hex2bin

(PHP >= 5.4.0)

hex2binConvert hex to binary

说明

string hex2bin ( string $data )

Converts the hex representation of data to binary

参数

data

Hexadecimal representation of data.

返回值

Returns the binary representation of the given data.

范例

Example #1 hex2bin() example

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

以上例程的输出类似于:

string(16) "example hex data"

参见


字符串函数
在线手册:中文 英文
PHP手册
PHP手册 - N: Convert hex to binary

用户评论:

azizsaleh at gmail dot com (23-Feb-2012 11:26)

Here is the alternative version:

if(!function_exists('hex2bin'))
    /**
     * Converts the hex representation of data to binary
     *
     * http://www.php.net/manual/en/function.hex2bin.php
     *
     * @param   string  $str        Hexadecimal representation of data
     *
     * @return  string              Returns the binary representation of the given data
     */
    public function hex2bin($data)
    {
        $bin    = "";
        $i      = 0;
        do {
            $bin    .= chr(hexdec($data{$i}.$data{($i + 1)}));
            $i      += 2;
        } while ($i < strlen($data));

        return $bin;
    }
}

Anonymous (23-Feb-2012 10:28)

The function pack("H*" , $hex_string); will not work as expected if $hex_string contains an odd number of hexadecimal digits.

For example:

echo ord(pack("H*", 'F'));

will return 240 not 15. Use pack("H*", '0F'); instead.

Anonymous (31-Aug-2011 09:32)

The function hex2bin does not exist in PHP5.
You can use 'pack' instead :

$binary_string = pack("H*" , $hex_string);