Skip to content

Instantly share code, notes, and snippets.

@zhengfan2014
Last active August 10, 2021 08:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhengfan2014/95f8fd9e4ee9186d7e246420ab85788f to your computer and use it in GitHub Desktop.
Save zhengfan2014/95f8fd9e4ee9186d7e246420ab85788f to your computer and use it in GitHub Desktop.
进制转换,二进制与十进制互转,php版本
// 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;
}
@zhengfan2014
Copy link
Author

修复传入值等于2时的bug

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment