Coming soon - Get a detailed view of why an account is flagged as spam!
view details

This post has been de-listed

It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.

8
Fastest way to pack an array of boolean values into bytes
Post Body

I have a large array of boolean values that I'd like to store efficiently in a binary file. The way I have been doing this is to arrange them in groups of 8 booleans (eg T,F,F,T,T,F,T,T), make them into a a string of ones and zeros (eg 10011011), then convert that to a decimal value (eg 155), then pack that into a byte. I repeat this process until I've converted all the boolean values to bytes.

The code I have looks something like this:

$binarydata=null;
$numbooleans=count($array_of_booleans);
for($i=0;$i<ceil($numbooleans/8);$i  ){
        $digits="";
        for($j=0;$j<8;$j  ){
            $counter=$i*8 $j;
            if($counter>=$numbooleans){
                $digits.="0";
            }else{
                if($array_of_booleans[$counter]){
                    $digits.="1";
                }else{
                    $digits.="0";
                }           
            }
        }
        $binarydata.=pack("C",bindec($digits)); 
}

I feel like this method is not efficient. Issues include:

  • starting with boolean values, then changing them into the zeros and ones as text. This seems unnecessary
  • eight lots of zeros and ones are temporarily stored as a string with 8 characters, is there a way to bypass this step?
  • the string with 8 characters is then they are implicitly cast to a binary number in the bindec() function.
  • my loop structure to join the values into groups of eight boolean values feels cumbersome

Ideally I'd like to construct the bytes in $binarydata as efficiently as possible. My $array_of_booleans contains tens of millions of values, so efficiency in this algorithm is important.

Can anyone suggest an alternate, more efficient method of converting $array_of_booleans to the $binarydata variable?

Author
Account Strength
100%
Account Age
18 years
Verified Email
Yes
Verified Flair
No
Total Karma
17,076
Link Karma
4,351
Comment Karma
12,427
Profile updated: 1 week ago
Posts updated: 8 months ago

Subreddit

Post Details

We try to extract some basic information from the post title. This is not always successful or accurate, please use your best judgement and compare these values to the post title and body for confirmation.
Posted
8 years ago