PHP bin2hex() Function

What is PHP bin2hex() Function?

If you want to convert each character of a string to its hexadecimal representation, use PHP bin2hex() function. The function actually converts ASCII value of each character to its hexadecimal value. For example, ASCII of “A” is 65 and hexadecimal of 65 is 41. So, the function converts “A” to 41.

Syntax:

bin2hex(string)

Parameters:

The Function has 1 parameter which is required –

string (Required): It specifies a string that you want to convert to its hexadecimal representation.

Return Values:

The function returns the hexadecimal representation of each character of the string.

Examples:

Example:

<?php
$string = "A";
echo "Hexadecimal representation of $string is: " . bin2hex("A");
?>

Output:

Hexadecimal representation of A is: 41

Notes on bin2hex() Function:

  • The function doesn’t consider the string as binary and doesn’t convert it to hexadecimal considering it as binary. Look at the example below. It doesn’t consider it as binary 10 and converts it to hexadecimal 2. Instead, it takes one character at a time and converts its ASCII to hexadecimal. So, first character “1”’s hexadecimal representation is 31. Similarly, “0” becomes 30.
    <?php
    echo bin2hex("10");
    ?>
    

    Output:

    3130

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP bin2hex() Function

bin2hex() function is one of the built-in string functions. Use this function to convert ASCII value of each character to its hexadecimal equivalent.

Reference:

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