Created
May 11, 2015 03:19
-
-
Save Lweek/064c87e4de71a5dd345b to your computer and use it in GitHub Desktop.
Smart binary operations in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// | |
// Bitwise operations can save memory! And looks smart! :) | |
// It is possible use short binary chain as settings registry | |
// Note: PHP 5.4+ knows how to use 0b binary format, older | |
// version can use bindec() function or just use your brain! | |
// | |
// @author Vladimir Belohradsky | |
// | |
// constants with binary numbers | |
define('STATUS_VENT', 1); // 0b001 | |
define('STATUS_DOOR', 2); // 0b010 | |
define('STATUS_BELL', 4); // 0b100 | |
// turn everything on (binary OR operation) | |
$status = STATUS_VENT | STATUS_DOOR | STATUS_BELL; | |
// turn doors off (binary NOT operation) | |
$status ^= STATUS_DOOR; | |
// check status chain where first number is position | |
// and second is 1 which is 0b1 in binary (binary AND operation) | |
if (($status >> 0) & 1) { | |
echo 'VENT is on', "\n"; | |
} | |
if (($status >> 1) & 1) { | |
echo 'DOOR is on', "\n"; | |
} | |
if (($status >> 2) & 1) { | |
echo 'BELL is on', "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment