Kcko
3/22/2019 - 8:22 PM

Bit operators - Johny

<?php

// For each flag, assign a power of two
// This makes a mask with a single bit turned on
$male = 1;
$bald = 2;
$tall = 4;
$funny = 8;
$fictitious = 16;

// To set flags, use OR
// Init John to male:
$john = $male;

// Set John to tall and fictitious
$john = $john | $tall | $fictitious;
// or $john |= $tall | $fictitious;


// To check if John is tall, use AND
if ( $john & $tall ) echo "You tall!
";
if ( ! ($john & $funny) ) echo "You not funny!
";
// or  if ( ($john & $tall) == $tall ) 
// because since $tall only has one bit set to 1,
// something & $tall is either 0 or $tall
// but comparing to zero is faster
// than checking for equality

// To flip tall, use XOR
$john = $john ^ $tall;
// or $john ^= $tall;
$not = ( $john & $tall ) ? "" : "not ";
echo "You ".$not."tall...
";

// To unset tall, use & with the complement
$john = $john & (~ $tall);
$not = ( $john & $tall ) ? "" : "not ";
echo "You ".$not."tall, dude.
";

// To invert all flags, use NOT (~):
$antijohn = ~ $john;
$not = ( $antijohn & $funny ) ? "" : "not ";
echo "You ".$not."funny, antijohn.
";