Binary to decimal conversion refers to the process of converting a binary number (i.e., a number represented by only two digits 0 and 1) to its equivalent decimal number (i.e., in the form of 10 as a base).
This article will explain how to convert the binary form of a number to a decimal form in PHP using different methods.
Binary numbers (Binary ) are composed only of 0 and 1 digits used by machines, and decimal numbers are decimal numbers used by humans. To convert a binary number to a decimal number, multiply each binary number by its position power (starting from 0 on the right), and add all the results.
Example 12) (0 × 21) (1 × 20) = 4 0 1 = 5
Example 23) (1 × 22) (1 × 21) (1 × 20) = 8 4 2 1 = 15
Example 3The following are different ways to perform binary to decimal conversion in PHP:
Binary to decimal conversion using built-in functions
bindec(), which can be used directly to convert binary numbers to decimal numbers.
Implementation steps<?php $binary = "101"; // 使用 bindec() 将二进制转换为十进制 $decimal = bindec($binary); echo "二进制数 '$binary' 的十进制等效值为:$decimal"; ?>
<code>二进制数 '101' 的十进制等效值为:5</code>
Time complexity: O(1) Space complexity: O(1)
Binary to decimal conversion using loops<?php $binary = "101"; // 使用 bindec() 将二进制转换为十进制 $decimal = bindec($binary); echo "二进制数 '$binary' 的十进制等效值为:$decimal"; ?>
<code>二进制数 '101' 的十进制等效值为:5</code>
Time complexity: O(n) Space complexity: O(1)
In this method, we directly use the bit operators supported by PHP to operate the bits. In this approach, we use displacement to calculate the decimal equivalent.
<?php $binary = "101"; $decimal = 0; $length = strlen($binary); // 循环遍历二进制数中的每个数字 for ($i = 0; $i < $length; $i++) { // 将二进制数字乘以 2^(从右起的位置) $decimal += $binary[$length - $i - 1] * pow(2, $i); } // 输出十进制等效值 echo "二进制数 '$binary' 的十进制等效值为:$decimal"; ?>
<code>二进制数 '101' 的十进制等效值为:5</code>
Time complexity: O(n) Space complexity: O(1)
The above is the detailed content of PHP Program for Binary to Decimal Conversion. For more information, please follow other related articles on the PHP Chinese website!