Jake
Jake

Reputation: 11430

What are the maximum limit of bitwise operation on large integers in PHP?

I just realized something useful and hope to share:

I am running PHP x86 on a 64bit Windows 7 machine. I was trying to do a permission system where I have a line like this:

// value of $role came from database i.e. 0xffffffff
// value of $function_ACL is hardcoded in PHP file using 32bit hex notation i.e. 0x80000000
// true if access is allowed
return ($function_ACL & $role) != 0

Somehow, the value of $role is converted using the rules of intval(), thereby reaching the integer limit, and the result is wrongly 0.

To get around this problem, I noticed we can do this

$function_ACL += 0;
$role += 0;
return ($function_ACL & $role) != 0 // works! which is odd, because type conversion don't follow the same routine

This leads me to wonder what really are the limits, then trialed a few very large numbers

// these numbers get converted to scientific notation
echo 0xffffffffffffffffffffffffffffffff;
echo 9999999999999999999999999999999999

// 52 bits (13 f's) is the max limit for a correct bitwise operation
echo (0xfffffffffffff & 0x0000000000001);

Anyone has more to contribute?

Upvotes: 0

Views: 1047

Answers (1)

Mikpa
Mikpa

Reputation: 1922

Take a look on gmp. It allows bitwise operations on large numbers.

$role = gmp_init("0xffffffff");
$function_ACL = gmp_init("0x80000000");
if (gmp_and($role, $function_ACL))
    echo "yes!";

Upvotes: 2

Related Questions