Skip to content

Instantly share code, notes, and snippets.

@gamikun
Created February 25, 2017 21:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gamikun/699785b315908e16ba2f7d6c71b5cdc0 to your computer and use it in GitHub Desktop.
Save gamikun/699785b315908e16ba2f7d6c71b5cdc0 to your computer and use it in GitHub Desktop.
Boolean bitpacking for PHP
<?php
/**
* Given an array of numbers (of 24 bits/hours),
* where each bit of the number is equal to 1 hour,
* validates if the corresponding hour and day is on.
*
* @param $days Array of ~24 bits numbers.
* @param $day Number from 0 to 7
* @param $hour 0 to 23
*
* @return bool
*/
function isHourOn($days, $day, $hour) {
return isset($days[$day])
and $days[$day] > 0
and (($days[$day] >> $hour) & 1);
}
/**
* Given an array of numbers, convert them to
* a number, where each number is validated to
* be different to 0 and them added to the bits
* of the result number.
*
* @param $hours Array of numbers.
*
* @return numeric
*/
function packHours($hours) {
$a = 0;
$i = 0;
foreach ($hours as $h) {
$a |= (($h > 0) << $i);
if (++$i >= 24)
break;
}
return $a;
}
/**
* Convert a ~24 bits number into an array
* of integers (0's and 1's)
*
* @param $pack Number of ~24bits
*
* @return Array
*/
function unpackHours($pack) {
$hrs = array_fill(0, 23, 0);
for ($i = 0; $i < 24; $i++) {
$hrs[$i] = ($pack >> $i) & 1;
}
return $hrs;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment