Last active
August 10, 2021 08:01
-
-
Save zhengfan2014/95f8fd9e4ee9186d7e246420ab85788f to your computer and use it in GitHub Desktop.
进制转换,二进制与十进制互转,php版本
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// eg: Twelve(29) => [1,1,1,0,1] | |
function Twelve($num) | |
{ | |
$num = (int)$num; | |
$result = []; | |
if ($num == 2) { | |
$result = [0, 1]; | |
} else { | |
while ($num>2) { | |
$result[]=$num%2; | |
$num = floor($num/2); | |
} | |
$result[]=$num%2; | |
} | |
$result = array_reverse($result); | |
return $result; | |
} | |
// eg: Lists2StringTen([1,1,1,0,1]) => 29 | |
function Lists2StringTen($list) | |
{ | |
$num_list = array_reverse($list); | |
$num = 0; | |
for ($i = 0; $i < count($num_list); $i++) { | |
if ($num_list[$i] == 1) { | |
$num += pow(2, $i); | |
} | |
} | |
return $num; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
修复传入值等于2时的bug