note 124080 added to language.operators.bitwise
| From: | ASchmidt at Anamera dot net | Date: | Mon, 29 Jul 2019 23:52:47 +0000 |
| Subject: | note 124080 added to language.operators.bitwise | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-211755@lists.php.net to get a copy of this message | ||
Setting, unsetting and testing single and multiple bits in a bitmask:
<?php
const FLAG_A = 0b0001,
FLAG_B = 0b0010,
FLAG_C = 0b0100,
FLAG_D = 0b1000;
const COMBO_BC = FLAG_B | FLAG_C;
$bitmask = 0b000;
// Setting individual flags.
$bitmask |= FLAG_B; // Sets FLAG_B (=2)
$bitmask |= FLAG_C; // also sets FLAG_C (=4)
// Testing single or multiple flags.
echo (bool)( $bitmask & FLAG_B ); // True, B is set.
echo (bool)( $bitmask & (FLAG_A | FLAG_B) ); // True, A or B is set.
echo (bool)( $bitmask & FLAG_B and $bitmask & FLAG_C ); // True, B and C are set.
echo (bool)( ( $bitmask & (FLAG_B | FLAG_C) ) ^ (FLAG_B | FLAG_C) ); // False if B and C are
set.
echo (bool)( ( $bitmask & COMBO_BC ) ^ COMBO_BC ); // False if B and C are set.
echo (bool)( $bitmask & FLAG_C and $bitmask & FLAG_D ); // False, C and D are NOT BOTH
set.
echo (bool)( ( $bitmask & (FLAG_C | FLAG_D) ) ^ (FLAG_C | FLAG_D) ); // True, if C and D are
NOT BOTH set.
// Resetting single flag.
$bitmask &= $bitmask ^ FLAG_B; // Unsets B
$bitmask &= $bitmask ^ FLAG_A; // A remains unset.
var_dump( $bitmask ); // Only C still set (=4)
// Resetting multiple flags.
$bitmask &= $bitmask ^ ( FLAG_C | FLAG_D ); // Unsets C and/or D
var_dump( $bitmask ); // No flags set (=0)
----
Server IP: 208.43.231.9
Probable Submitter: 119.81.81.244 (proxied: 173.63.128.218)
----
Manual Page -- http://php.net/manual/en/language.operators.bitwise.php
Edit -- https://master.php.net/note/edit/124080
Del: integrated -- https://master.php.net/note/delete/124080/integrated
Del: useless -- https://master.php.net/note/delete/124080/useless
Del: bad code -- https://master.php.net/note/delete/124080/bad+code
Del: spam -- https://master.php.net/note/delete/124080/spam
Del: non-english -- https://master.php.net/note/delete/124080/non-english
Del: in docs -- https://master.php.net/note/delete/124080/in+docs
Del: other reasons-- https://master.php.net/note/delete/124080
Reject -- https://master.php.net/note/reject/124080
Search -- https://master.php.net/manage/user-notes.php