PHP - bin2hex() Function



The PHP bin2hex() function is used to convert a binary (i.e., strings of binary data) data into a hexadecimal representation. It other words, it converts a string of ASCII character to a string of hexadecimal values.

A "hexadecimal" number is a number in a numerical system with a base of 16. Here, each digit can be represented by the symbols 0 to 9 and A to F.

This function does not convert strings that represent binary digits (e.g. "1010" or "1100") into hexadecimal values. See also pack()

Syntax

Following is the syntax of the PHP bin2hex() function −

bin2hex(string $str): string 

Parameters

This function accepts a single parameters, which is described below −

  • str − A string that needs to converted into hexadecimal.

Return Values

This function returns the hexadecimal representation of the provided string.

Example 1

The following is the basic example of the PHP bin2hex() function −

<?php
   $str = "Tutorialspoint";
   echo "The given string: $str";
   echo "\nHexadecimal representation: ";
   #using bin2hex() function
   var_dump(bin2hex($str));
?>

Output

This will produce the following output −

The given string: Tutorialspoint
Hexadecimal representation: string(28) "5475746f7269616c73706f696e74"

Example 2

Following is another example of the PHP bin2hex() function. We use this function to retrieve a hexadecimal representation of this string "Hello World!" −

<?php
   $str = "A";
   echo "The given string: $str";
   echo "\nHexadecimal representation: ";
   #using bin2hex() function
   var_dump(bin2hex($str));
?>

Output

Following is the output of the above program −

The given string: A
Hexadecimal representation: string(2) "41"
php_function_reference.htm
Advertisements