Dave Z
Dave Z

Reputation: 159

How can I make this bitwise code work?

bitwise operators only work on integers in PHP and the maximum size of an integer is 2^63 on 64bit servers. If I create a value greater than that it will cast my variable to a float and bitwise operators will stop functioning. I have the following example:

<?php

$CAN_DANCE = 2;

$CAN_SING = 4;

$CAN_PLAY = 8;

$CAN_BEGOD = pow(2,64);

$userperms =  $CAN_PLAY | $CAN_DANCE | $CAN_SING | $CAN_BEGOD;

if($userperms & $CAN_DANCE)
    echo 'This will work';

if($userperms & $CAN_BEGOD)
    echo 'This will not work';

?>

Naturally it will return true for the first check as thats less than 2^63 however for the latter I assign it to 2^64 which is too great for an integer and it incorrectly returns false. Is there any way to make it work for greater than 2^63? Otherwise I will only be able to use bitperms for upto 63 different items only.

Upvotes: 1

Views: 898

Answers (3)

Nathan
Nathan

Reputation: 3

You could try using a bit array:

$bitArray = array();
$bitArray[0] = $word0;
$bitArray[1] = $word1;
. 
.
.

If you need $nFlags bits and $bitsPerWord = 64, then you'll create $nFlags/$bitsPerWord words.

Upvotes: 0

hakre
hakre

Reputation: 197564

GMP comes to mind, this is encapsulated (see full code/demo):

$CAN_DANCE = Gmp(2);

$CAN_SING = Gmp(4);

$CAN_PLAY =  Gmp(8);

$CAN_BEGOD = Gmp(2)->pow(64);    

$userperms = Gmp($CAN_PLAY)->or($CAN_DANCE, $CAN_SING, $CAN_BEGOD);    

if($userperms->and($CAN_DANCE)->bool())
    echo 'This will work', "\n";

if($userperms->and($CAN_BEGOD)->bool())
    echo 'This will work', "\n";

This will work with much larger numbers, however, the numbers are resources (Gmp::number()) or strings ((string) Gmp) and as long as each instance lives, the Gmp object as well.

Upvotes: 1

Alon Eitan
Alon Eitan

Reputation: 12025

Because this function return int, maybe you could you use the gmp_pow() function, and to calculate the rusults you can use the gmp_or() and for the if steatments you can use gmp_and()

Upvotes: 0

Related Questions