PHP bin2hex() Function

Usage — The PHP bin2hex() function is used to encode a binary string into hexadecimal representation. In other words, you can use this function to convert a string of ASCII characters to hexadecimal values.

It has the following syntax:


string bin2hex ( string $str )

Here is an example of using bin2hex():


$str = bin2hex("Good Morning!");

// Output — 476f6f64204d6f726e696e6721

Return Value — This function returns the hexadecimal representation of the given string. The conversion is done byte-wise with the high-nibble first.

PHP Version and Changelog — The bin2hex() function is available in PHP 4, PHP 5, PHP 7.

Relevant Functions — Other related PHP functions that you should know about are: hex2bin() which decodes a hexadecimally encoded binary string and pack() which packs data into binary string.

Go Directly To — usage, parameters, working examples or additional tips.



The str parameter is used to specify the string that you want to convert. This is a required parameter.

Working Examples

Here are some examples of using the bin2hex() function:


$str = bin2hex("ABCDabcd1234");

// Output — 414243446162636431323334

Additional Tips

Here are some of the most upvoted tips taken from the comment section of the PHP manual:

  1. This function is for converting binary data into a hexadecimal string representation. This function is not for converting strings representing binary digits into hexadecimal. If you want that functionality, you can simply do this:


    $binary = "11111001";
    $hex = dechex(bindec($binary));
    // Output — f9
    echo $hex;

    This would output “f9”. Just remember that there is a very big difference between binary data and a string representation of binary.

    Suggested by - tehjosh at gamingg dot net

  2. In an attempt to dodge spam bots I’ve seen people (including myself) hex encode their email addresses in “mailto” tags. This is the small chunk of code I wrote to automate the process:


    function hex_encode ($email_address)    {
        $encoded = bin2hex("$email_address");
        $encoded = chunk_split($encoded, 2, '%');
        $encoded = '%' . substr($encoded, 0, strlen($encoded) - 1);
        return $encoded;

    So for example,


    <a href="mailto:&lt;?=hex_encode("")">email me</a>

    would produce the following address:



    Suggested by - pedram at redhive dot com

Further Reading

  1. You can read more about the PHP bin2hex() function on

Reader Comments

1. You can register or login to post a comment. Asking readers to register improves the quality of discussion.

2. As a registered user, you will also get to access features like choosing between a light and dark theme or anything else that we might implement in future.

Follow Us For Updates

Go To Top