问题描述
我发现在php.net此功能。这似乎在正数的工作,但未能对消极的:
I found this function at php.net. It seems to work on positive numbers, but fails on negative ones:
function gmp_shiftr($x,$n) { // shift right
return(gmp_div($x,gmp_pow(2,$n)));
}
echo -1 >> 8; //returns -1, presumably correctly
echo "<br />";
echo gmp_strval(gmp_shiftr(-1,8)); //returns 0, presumably incorrectly
我怎么能修复了底片工作中的作用?
How could I fix up the function to work with negatives?
两个想法我有:
也许我可以做线沿线的东西。
Maybe I could do something along the lines of
if (whatever) { $a >> $b} else{ gmp_shiftr($a, $b) }?
或者,也许我可以根据自己的价值减去负的成绩东西..?
Or, maybe I could subtract something from the negative results depending on their value..?
我只想得到>>将给予价值,也得到它> 32位数字,当我使用GMP。
I just want to get the value that >> would give, but also get it for >32bit numbers when I use GMP.
推荐答案
综观的的GMP文件,有一个函数
Looking at the GMP documentation for the division routines, there's a function
void mpz_tdiv_q_2exp (mpz_t q, mpz_t n, unsigned long int b)
这看起来可能是你想要什么:算术右移的治疗 N
,如果它被重新presented在二进制补码,和(我认为)转变为 B
地方
在右边。不幸的是,API的那个水平似乎并没有被PHP GMP暴露出来。
that seems like it might be what you want: an arithmetic right shift that treatsn
as if it were represented in twos-complement, and (I think) shifts it b
placesto the right. Unfortunately, that level of the API doesn't seem to be exposed by PHP GMP.
我发现了一个做符号扩展时比特数
中联重presentation是未知的:
I found a bit twiddling hack for doing sign extension when the number of bitsin the representation is unknown:
unsigned b; // number of bits representing the number in x
int x; // sign extend this b-bit number to r
int r; // resulting sign-extended number
int const m = 1U << (b - 1); // mask can be pre-computed if b is fixed
x = x & ((1U << b) - 1); // (Skip this if bits in x above position b are already zero.)
r = (x ^ m) - m;
由于按位与和XOR的是的由PHP支持GMP,你也许能够使
这项工作......
Since bitwise AND and XOR are supported by PHP GMP, you might be able to makethis work...
这篇关于GMP位移位不能在负数运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!