Get Integer Bit Parity In PHP

I was forced to use php to generate a cyclic redundancy check (CRC) byte earlier this week. When generating this CRC I needed to check the bit parity of a byte. At first I thought that there would be an example that I could just cut and paste into my code or a library including the function somewhere. I guess that most PHP users don’t really have to work with bits and bytes very often because I couldn’t find an example of doing this. Granted I didn’t really search that hard because writing it was pretty simple. But hopefully the next guy searching for this actually finds this example.

Most of the time we don’t really have to think about types in php. But if you’re dealing with this kind of thing then you usually want to know what you’re working with. This php function example will only work with integers and will return a value of -1 if the first parameter is not a number. The function returns 1 if the number of bits set in the number pased in is odd. Otherwise it will return 0. The second parameter defaults to 4 because that is the number of bytes in a normal php integer. In php if a number becomes larger than an integer can handle, which is called an overflow, it becomes a float. The default integer size is platform dependant but it’s usually 4 bytes. It can be set using the constant PHP_INT_SIZE if you need to change it.


<?php

function odd_parity($something,$number_of_bytes_to_check=4,$double_check=0)
{
    //test to make sure it's a number
    if(!is_numeric($something)) {return -1;}  

    $setbits = 0;

    //get the number of bits that are set
    for($i=0;$i<$number_of_bytes_to_check*8;$i++)
    {
        if($something & (1<<$i)) $setbits++;
    }

    //check if the number of bits set is even or odd   
    $result =  $setbits % 2;
   
    //spit out the results to double check it's working 
    if($double_check)
    echo   "<br>Parity of : ".$something." is ".
    $result." In Binary : ".decbin((int)$something).
    " Checking the right ".($number_of_bytes_to_check*8).
    " Bits";

    return $result;
}

//will return 0 because it's defaulting to 4 bytes
echo odd_parity(0x0100010001);  

?>

Share

2 Responses to “Get Integer Bit Parity In PHP”