PHP hex2bin() Function

What is PHP hex2bin() Function?

If you want to decode a encoded hexadecimal string back to its binary representation (which translates to ASCII value), use hex2bin() function.

How PHP hex2bin() Function works?

The function considers characters in a string as hexadecimal characters and process two characters at a time and converts this to 1 byte binary data.

Syntax:

hex2bin(string)

Parameters:

The Function has 1 parameter which is required –

string (Required): It specifies a string that represents a hexadecimal value.

Return Values:

aaa

Examples:

Example 1:

<?php
$hex = "41";
echo "Binary representation of the hexadecimal $hex is: " . hex2bin($hex);
?>

Output:

Binary representation of the hexadecimal 41 is: A

Notes on hex2bin() Function:

  • The function doesn’t convert a hexadecimal number to binary number. Look at the example below. The binary of the hexadecimal 41 is 01000001. But, the function converts it to “A”, because, it processes the 2 digits at a time, not process separately.
    <?php
    echo hex2bin("41");
    ?>
    

    Output:

    A
  • If you want to convert a hexadecimal number to its binary number, use base_convert() function-
    <?php
    $hex = "41";
    echo "Binary number of the hexadecimal $hex is: " . base_convert($hex, 16, 2);
    ?>
    

    Output:

    Binary number of the hexadecimal 41 is: 1000001

Caution:

  • If the input string’s length is odd, the function generates a warning-
    <?php
    $hex = "414";
    echo "Binary representation of the hexadecimal $hex is: " . hex2bin($hex);
    ?>
    

    Output:

    Warning: hex2bin(): Hexadecimal input string must have an even length in …\ hex2bin.php on line 3
    Binary representation of the hexadecimal 414 is:
  • If the input has any invalid hexadecimal number, the function generates a warning-
    <?php
    $hex = "$4";
    echo "Binary representation of the hexadecimal $hex is: " . hex2bin($hex);
    ?>
    

    Output:

    Warning: hex2bin(): Input string must be hexadecimal string in …\hex2bin.php on line 3
    Binary representation of the hexadecimal $4 is:

    Explanation:

    Valid hexadecimal characters are – 0 1 2 3 4 5 6 7 8 9 a b c d e f. Here, $ is not a valid hexadecimal character.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP hex2bin() Function

Hex2bin() function is one of the built-in string functions. Use this function to decode an encoded hexadecimal value to its binary representation.

Reference:

https://www.php.net/manual/en/function.hex2bin.php