Jack Smit
Jack Smit

Reputation: 3113

PHP Left bit shift issue on 32 bit

I am running into the issue where I need to do a << on a 32 bit machine and the number is already pretty big. If I shift on this big number the answer is incorrect, any way I can get past this?

I am pretty sure that the laptop is running Windows7 64 bit but PHP_INT_MAX produces 2147483647. Is there any way to set the php to use 64 bits? I am running XAMPP server on this laptop and I have to do some bit shifting on numbers, if the numbers are shifted too many times I get an incorrect answer.

Thanks in advance. Jack

Upvotes: 1

Views: 1708

Answers (2)

user5519200
user5519200

Reputation: 1

function logical_right_shift( $val , $shft ) {
    return floor(($val / pow(2,$shft)));
}

function logical_left_shift( $val , $shft ) {
    return ($val * pow(2,$shft));
}   

Upvotes: 0

Gordon Bailey
Gordon Bailey

Reputation: 3911

From the reference

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.

So no, you can't set it to use 64 bits.

It seems like the GMP functions might be what you need. Someone has posted a tip on this page for doing bitwise shifting with them:

Also, for those who wish to do bitwise shifting, it's quite simple.. to shift left, just multiply the number by pow(2,x), and to shift right, divide by pow(2,x).

<?php 
function gmp_shiftl($x,$n) { // shift left 
  return(gmp_mul($x,gmp_pow(2,$n))); 
} 

function gmp_shiftr($x,$n) { // shift right 
  return(gmp_div($x,gmp_pow(2,$n))); 
} 
?> 

Upvotes: 1

Related Questions