PHP function bin2hex – Convert binary data into hexadecimal representation

The bin2hex() function converts a string of ASCII characters to hexadecimal values. This was introduced in PHP3. This function Converts binary to a hexadecimal (base-16) value. Up to a 32-bit number, or 2,147,483,647 decimal, can be converted. Note that any value passed to the function is converted to an ASCII string (if possible). The string can be converted back using pack().

Syntax:

bin2hex(string $string): string

Parameters

Parameter Description
string A string.

Return Values

Returns the hexadecimal representation of the given string.

Examples

Example 1: Demonstrate how bin2hex() converts a string:

<?php 
$string = "I'm a geek and I'm ok...\n"; 

// Convert a string to its hex representation 
$hex_string = bin2hex ($string); 
echo $hex_string, "\n"; 

Output:

49276d2061206c756d6265726a61636b20616e642049276d206f6b2e2e2e0a 
I'm a geek and I'm ok... 

Example 2: Show how bin2hex() deals with non-character data:

<?php 
// Show how bin2hex() handles non-strings 
echo "bin2hex ('1') returns: " . bin2hex ('1') . "\n"; 

// It converts non-character data to an ASCII string 
echo "bin2hex (1) returns: " . bin2hex (1) . "\n"; 
// Can you tell the difference? 
// To make bin2hex() show the hex value of 1, use octal escape sequence 
echo 'bin2hex ("\1") returns: ' . bin2hex ("\1") . "\n"; 

// Try converting a character outside the range of the ASCII character table 
echo 'bin2hex ("\400") returns: ' . bin2hex ("\400") . "\n"; 
?>

Output:

bin2hex ('1') returns: 31 
bin2hex (1) returns: 31 
bin2hex ("\1") returns: 01 
bin2hex ("\400") returns: 00 
Related Post