我不知道在野外有任何Python到PHP的转换器,但是移植它应该是一件轻而易举的事,相似之处很容易发现:
function calcNumEntropyBits($s) { if (strlen($s) <= 0) return 0.0; $symCount = array(); foreach (str_split($s) as $c) { if (!in_array($c,$symCount)) $symCount[$c] = 1; else $symCount[$c] ++; } $entropy = 0.0; foreach ($symCount as $c=>$n) { $prob = $n / (float)strlen($s); $entropy += $prob * log($prob)/log(2); } if ($entropy >= 0.0) return 0.0; else return -($entropy*strlen($s));}function testEntropy($s): printf("Bits of entropy in '%s' is %.2f",$s,calcNumEntropyBits($s));testEntropy('hello world');testEntropy('bubba dubba');testEntropy('aaaaaaaaaaa');testEntropy('aaaaabaaaaa');testEntropy('abcdefghijk');
第一个函数的最后几行也可以写成标准的PHP三元表达式:
return ($entropy >= 0.0)? 0.0: -($entropy*strlen($s));
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)