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

How to convert string from hexadecimal to binary in PHP?

藏色散人
Release: 2023-04-05 17:44:01
Original
11400 people have browsed it

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"
?>
Copy after login

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"
?>
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template