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.
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 a Lead Software Engineer at Naukri.com. He passed out of Delhi College of Engineering in 2016 and likes to play Foosball. He loves traveling and is an exercise freak. His expertise includes Java, PHP, Python, Databases, Design and Architecture.