php - GMP Bit shift doesn't work on negative numbers -


i found function @ php.net. seems work on positive numbers, 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 fix function work negatives?

two ideas have:

maybe along lines of

if (whatever) { $a >> $b} else{ gmp_shiftr($a, $b) }? 

or, maybe subtract negative results depending on value..?

i want value >> give, >32bit numbers when use gmp.

looking @ gmp documentation division routines, there's function

void mpz_tdiv_q_2exp (mpz_t q, mpz_t n, unsigned long int b) 

that seems might want: arithmetic right shift treats n if represented in twos-complement, , (i think) shifts b places right. unfortunately, level of api doesn't seem exposed php gmp.

i found bit twiddling hack doing sign extension when number of bits in representation unknown:

unsigned b; // number of bits representing number in x int x;      // sign extend b-bit number r int r;      // resulting sign-extended number int const m = 1u << (b - 1); // mask can pre-computed if b fixed  x = x & ((1u << b) - 1);  // (skip if bits in x above position b zero.) r = (x ^ m) - m; 

since bitwise , and xor are supported php gmp, might able make work...


Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -