String Functions

PHP bin2hex() Function

Topic: PHP String ReferencePrev|Next


The bin2hex() function converts a string to hexadecimal value.

The following table summarizes the technical details of this function.

Return Value: Returns the hexadecimal representation of the given string.
Version: PHP 4+


The basic syntax of the bin2hex() function is given with:


The following example shows the bin2hex() function in action.

// Sample string
$str = "Hello World!";

// Converting to hexadecimal
echo bin2hex($str);

This function is for converting binary string into a hexadecimal string representation. This function is not for converting strings representing binary digits into hexadecimal.

// Sample data
$binary = "11110010"; // binary value of hex f2

// Converting to hexadecimal
echo bin2hex($binary)."<br>"; // Prints: 3131313130303130
echo dechex(bindec($binary)); // Prints: f2


The bin2hex() function accepts the following parameter.

Parameter Description
string Required. Specifies the string to be converted.

More Examples

Here're some more examples showing how bin2hex() function actually works:

In the following example the binary data first converted into hexadecimal representation, then it is converted back to the binary string using the pack() function.

// Sample string
$str = "Hello World!";

// Converting to hexadecimal
$hex = bin2hex($str);
echo $hex . "<br>";

// Converting hex to binary string
$data = pack("H*", $hex);
echo $data;

Tip: The format string "H*" consists of format code H which specifies hex string, high nibble first, and the repeater * which specifies repeating to the end of the input data.

Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties