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.
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?
Post Details
- Posted
- 8 years ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/PHP/comment...