1

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

2 Answers 2

1

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))); 
} 
?> 
3
  • You beat me to it. I was going to say the same thing, showing a bcmath code sample instead. Jan 3, 2013 at 4:10
  • I have no idea how that is going to help me? If I am limited to 32 bit and I call: $bitString = $bitString << 5; where $bitString is 10183165152 I am pretty much stuck? Am I missing something in your suggestion?
    – Jack Smit
    Jan 3, 2013 at 16:34
  • You would use GMP numbers, which are arbitrary precision, rather than php's fixed size ints. You can create GMP numbers with GMP init. Also, as @PleaseStand suggested, you could also use bcmath to accomplish the same thing, as it also provides arbitrary precision math. Jan 3, 2013 at 21:19
0
function logical_right_shift( $val , $shft ) {
    return floor(($val / pow(2,$shft)));
}

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.