开发者

How can I make this bitwise code work?

开发者 https://www.devze.com 2023-04-05 08:40 出处:网络
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 operat

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 t开发者_高级运维rue 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.


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.


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()


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号