hex2bin

(PHP >= 5.4.0)

hex2binDecodes a hexadecimally encoded binary string

Descrição

string hex2bin ( string $data )

Decodes a hexadecimally encoded binary string.

Cuidado

This function does NOT convert a hexadecimal number to a binary number. This can be done using the base_convert() function.

Parâmetros

data

Hexadecimal representation of data.

Valor Retornado

Returns the binary representation of the given data ou FALSE em caso de falha.

Erros

If the hexadecimal input string is of odd length or invalid hexadecimal string an E_WARNING level error is thrown.

Changelog

Versão Descrição
5.5.1 A warning is thrown if the input string is invalid hexadecimal string.
5.4.1 A warning is thrown if the input string is of odd length. In PHP 5.4.0 the string was silently accepted, but the last byte was truncated.

Exemplos

Exemplo #1 hex2bin() example

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

O exemplo acima irá imprimir algo similar à:

string(16) "example hex data"

Veja Também

  • bin2hex() - Converte um dado binário em representação hexadecimal
  • unpack() - Unpack data from binary string

add a note add a note

User Contributed Notes 8 notes

up
22
Anonymous
2 years ago
The function hex2bin does not exist in PHP5.
You can use 'pack' instead :

$binary_string = pack("H*" , $hex_string);
up
1
Johnson
1 year 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
carschrotter at gmail dot com
9 months 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
0
jarismar dot php at gmail dot com
1 year ago
A way to convert hex strings in the form "0x123ABC" to integer is to use the function base_convert("0x123ABC", 16, 10)
up
-1
EM
2 months 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.
up
0
Anonymous
2 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
-1
walf
10 months 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
-1
jannik [dot] zappe [at] udo [dot] edu
11 months 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;
    }
}
?>
To Top