• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer navigation

The Geek Diary

  • OS
    • Linux
    • CentOS/RHEL
    • Solaris
    • Oracle Linux
    • VCS
  • Interview Questions
  • Database
    • oracle
    • oracle 12c
    • ASM
    • mysql
    • MariaDB
  • DevOps
    • Docker
    • Shell Scripting
  • Big Data
    • Hadoop
    • Cloudera
    • Hortonworks HDP

PHP function bin2hex – Convert binary data into hexadecimal representation

by admin

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 

Filed Under: PHP

Some more articles you might also be interested in …

  1. PHP atan2 function – Arc tangent of two variables
  2. PHP ceil function – Round fractions up
  3. PHP Function str_split() – Convert a string to an array
  4. PHP bindec function – Convert a number between arbitrary bases
  5. PHP Function strchr() – Alias of strstr()
  6. PHP asin function – Arc sine
  7. PHP connection_status function – Returns connection status bitfield
  8. PHP function str_ireplace() – Case-insensitive version of str_replace()
  9. PHP function strcmp() – Binary safe string comparison
  10. PHP decbin function – Decimal to binary

You May Also Like

Primary Sidebar

Recent Posts

  • fprintd-delete Command Examples in Linux
  • fprintd-delete: command not found
  • foreman: command not found
  • foreman Command Examples in Linux

© 2023 · The Geek Diary

  • Archives
  • Contact Us
  • Copyright