PHP bin2hex is an inbuilt function in PHP. It converts strings to hexadecimal values byte-wise with the high-nibble first. However, it does not convert strings representing binary digits to hexadecimal. In this article, we will discuss the PHP bin2hex Function. Also, we will discuss a few examples of using it.
Also, for converting a hexadecimal sequence back to a string, you may use the PHP hex2bin Function.
Remember: There is a very big difference between binary data and a string representation of binary.
The function expects only one parameter. The binary string which needs to be converted to hexadecimal values is the input to the function.
The function returns the hexadecimal value of the input string. However, it does not convert strings containing binary values to hexadecimal.
Input: bin2hex('concatly') Output: 636f6e6361746c79
Let’s discuss a few examples of using the function.
Example 1: Simple String
You can convert a simple string to hexadecimal values using the function.
<?php $string = 'concatly'; echo bin2hex($string); ?>
Example 2: String Representation of Binary
However, you cannot use the function to convert a string representation of binary to hexadecimal values directly.
<?php $string = '11111001'; echo bin2hex($string); ?>
This will print the following and not ‘f9’.
Vishesh is currently working as an Intermediate Software Engineer with Orion Health, New Zealand. He graduated with a Masters in Information Technology from the University of Auckland in 2021. With more than 4 years of work experience, his expertise includes Java, Python, Machine Learning, PHP, Databases, Design and Architecture.