Home  >  Article  >  Backend Development  >  How to convert string from hexadecimal to binary in PHP?

How to convert string from hexadecimal to binary in PHP?

藏色散人
藏色散人Original
2019-03-25 13:39:0511354browse

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.

How to convert string from hexadecimal to binary in PHP?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn