函數(shù)名:gmp_popcount()
適用版本:PHP 5 >= 5.6.1, PHP 7, PHP 8
用法:gmp_popcount(string|int|GMP $num): int
說(shuō)明:gmp_popcount() 函數(shù)用于計(jì)算給定整數(shù)的二進(jìn)制表示中設(shè)置的位數(shù)(即二進(jìn)制位為1的個(gè)數(shù))。
參數(shù):
- $num:要計(jì)算二進(jìn)制位數(shù)的整數(shù)??梢允且粋€(gè)字符串、整數(shù)或 GMP 對(duì)象。
返回值:返回一個(gè)整數(shù),表示給定整數(shù)的二進(jìn)制表示中設(shè)置的位數(shù)。
示例:
// 示例 1
$num1 = 10; // 二進(jìn)制表示為 1010
$result1 = gmp_popcount($num1);
echo $result1; // 輸出 2
// 示例 2
$num2 = "100110"; // 二進(jìn)制表示為 100110
$result2 = gmp_popcount($num2);
echo $result2; // 輸出 4
// 示例 3
$num3 = gmp_init("1111", 2); // 二進(jìn)制表示為 1111
$result3 = gmp_popcount($num3);
echo $result3; // 輸出 4
注意:在 PHP 7.4 之前的版本中,只能接受整數(shù)類型的參數(shù)。在 PHP 7.4 及之后的版本中,可以接受字符串和 GMP 對(duì)象作為參數(shù)。