Home > Article > Backend Development > How to convert string from hexadecimal to binary in PHP?
PHP converts a string from hexadecimal to binary by using the hexdec(), decbin() or base_convert() functions. The hexdec() function converts hexadecimal to decimal, and the decbin() function uses For converting decimal to binary. The base_convert() function is used to convert numbers between arbitrary bases.
The following are two methods of using PHP built-in functions to convert hexadecimal strings to binary strings:
Method 1
Use hexdec to convert a hexadecimal string to a numeric binary, and then use decbin to convert a numeric binary value to a binary string:
<?php $hexString = "1f"; $binNumeric = hexdec($hexString); $binString = decbin($binNumeric); // = "11111" ?>
Note: The hexdec() function converts the hexadecimal string into a binary string. Convert hexadecimal to decimal. The decbin() function is used to convert decimal to binary.
Method 2
Use base_convert to directly convert a hexadecimal string into a binary string:
<?php $hexString = "ff"; $binString = base_convert($hexString,16,2); // = "11111111" ?>
Note: The base_convert() function is used Convert numbers between arbitrary bases.
Related recommendations: "PHP Tutorial"
The above is the detailed content of How to convert string from hexadecimal to binary in PHP?. For more information, please follow other related articles on the PHP Chinese website!