开发者

Using GMP bitshift with negative numbers

开发者 https://www.devze.com 2023-03-22 09:38 出处:网络
echo -1 >> 8; //returns -1 function gmp_shiftr($x,$n) { // shift right return(gmp_div($x,gmp_pow(2,$n)));
echo -1 >> 8; //returns -1

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

echo gmp_strval(gmp_shiftr(-1, 8)); //returns 0

I'm trying to get the same return values I would otherwise get from bitwise operators on a 64 bit machine with the GMP functions but it doesn't do that on negative numbers.

I asked a pretty much identical question a while ago, but that thread completely died. The top answer basically suggested that I edit the C code underlying PHP, but since I'm on managed hosting, I'm unable to mess with the source code (not to mention the lac开发者_StackOverflowk of portability in such a solution).

I'm using GMP functions because I need to deal with larger numbers that 32-bit systems don't give the right results on. I also tried using the BC math functions but they have the same issue with negative #s.


Your implementation of right shift is not correct. The right shift gives the same results as a division with a power of two as long as the result is not greater that -1 for negative numbers. This is clear in the examples given in the php manual:

http://php.net/manual/en/language.operators.bitwise.php

A solution would be to check whether the given $x is negative, but greater than -2^$n and, if so, return -1 directly.

0

精彩评论

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