Home >Backend Development >PHP Problem >How to convert binary to decimal in php

How to convert binary to decimal in php

青灯夜游
青灯夜游Original
2021-12-10 18:43:403075browse

php method to convert binary to decimal: 1. Use the bindec() function, the syntax "bindec($binary_string)"; 2. Use the base_convert() function, the syntax "base_convert($binary_string,2,10 )".

How to convert binary to decimal in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php converts binary For decimal

1, use the bind() function

bindec($binary_string) function to convert the binary number$binary_stringConvert to decimal number.

<?php
echo bindec("0011") . "<br>";
echo bindec("01") . "<br>";
echo bindec("11000110011") . "<br>";
echo bindec("111");
?>

Output result:

How to convert binary to decimal in php

2. Use base_convert() function

base_convert() Function converts numbers between arbitrary bases.

base_convert($binary_string,$frombase,$tobase);
  • $binary_string Required. Specifies the binary number to be converted.

  • #$frombase Required. Specifies the original base of the number. Between 2 and 36 (inclusive). Numbers above decimal are represented by the letters a-z, such as a for 10, b for 11, and z for 35.​

  • #$tobase Required. Specifies the base to be converted. Between 2 and 36 (inclusive). Numbers above decimal are represented by the letters a-z, such as a for 10, b for 11, and z for 35.​

<?php
header("content-type:text/html;charset=utf-8");
$num1="0011";
$num2="11000110011";
echo "二进制 ".$num1." 转换成十进制 ".base_convert($num1,2,10)."<br>"; 
echo "二进制 ".$num2." 转换成十进制 ".base_convert($num2,2,10)."<br>"; 
?>

Output results:

How to convert binary to decimal in php

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to convert binary to decimal 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