PHP code example of yaroslavche / bitmask

1. Go to this page and download the library: Download yaroslavche/bitmask library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yaroslavche / bitmask example snippets


define('READ', 1 << 0);
define('WRITE', 1 << 1);
define('EXECUTE', 1 << 2);

$mask = READ | WRITE | EXECUTE;
echo sprintf('mask: %d', $mask); // mask: 7
if ($mask & READ) {} // if $mask has a single bit READ
$mask ^= EXECUTE; // remove a single bit from the $mask
$mask |= EXECUTE; // set a single bit to the $mask

use BitMask\BitMask;

// two arguments: integer mask (default: 0) and most significant bit for boundaries (default: null) 
$bitmask = new BitMask(READ | WRITE | EXECUTE);
echo sprintf('mask: %d', $bitmask->get()); // mask: 7
if ($bitmask->has(READ)) {}
$bitmask->remove(EXECUTE);
$bitmask->set(EXECUTE);

use BitMask\EnumBitMask;

enum Permissions
{
    case READ;
    case WRITE;
    case EXECUTE;
}

// two arguments: bitmask->has(Permissions::READ)) {}
$bitmask->remove(Permissions::EXECUTE);
$bitmask->set(Permissions::EXECUTE);

$bitmask->set(Unknown::Case); // throws an exception, only Permissions cases available

use BitMask\Util\Bits;

$mask = 7; // 1 << 0 | 1 << 1 | 1 << 2
$integerMostSignificantBit = Bits::getMostSignificantBit($mask); // int 2
$arraySetBitsIndexes = Bits::getSetBitsIndexes($mask); // array:3 [0, 1, 2]
$arraySetBits = Bits::getSetBits($mask); // array:3 [1, 2, 4]
$string = Bits::toString($mask); // string "111"
$integerBit = Bits::indexToBit(16); // int 65536
$integerIndex = Bits::bitToIndex(65536); // int 16
$boolIsSingleBit = Bits::isSingleBit(8); // true