Tower
Tower

Reputation: 102905

Calculating 0's and 1's in PHP

I want to calculate Frequency (Monobits) test in PHP:

Description: The focus of the test is the proportion of zeroes and ones for the entire sequence. The purpose of this test is to determine whether that number of ones and zeros in a sequence are approximately the same as would be expected for a truly random sequence. The test assesses the closeness of the fraction of ones to ½, that is, the number of ones and zeroes in a sequence should be about the same.

I am wondering that do I really need to calculate the 0's and 1's (the bits) or is the following adequate:

$value = 0;

// Loop through all the bytes and sum them up.
for ($a = 0, $length = strlen((binary) $data); $a < $length; $a++)
    $value += ord($data[$a]);

// The average should be 127.5.
return (float) $value/$length;

If the above is not the same, then how do I exactly calculate the 0's and 1's?

Upvotes: 1

Views: 94

Answers (1)

phihag
phihag

Reputation: 288070

No, you really need to check all zeroes and ones. For example, take the following binary input:

01111111 01111101 01111110 01111010

. It is clearly (literally) one-sided(8 zeroes, 24 ones, correct result 24/32 = 3/4 = 0.75) and therefore not random. However, your test would compute 125.0 /255 which is close to ½.

Instead, count like this:

function one_proportion($binary) {
    $oneCount = 0;
    $len = strlen($binary);
    for ($i = 0;$i < $len;$i++) {
        $intv = ord($binary{$i});
        for ($bitp = 0;$bitp < 7;$bitp++) {
            $oneCount += ($intv>>$bitp) & 0x1;
        }
    }
    return $oneCount / (8 * $len);
}

Upvotes: 2

Related Questions