Using bit operations on 64 bits integers in 32 bit systems (no php_gpm extension)

StackOverflow https://stackoverflow.com/questions/4367469

  •  09-10-2019
  •  | 
  •  

Pergunta

I found some solution Efficient way of doing 64 bit rotate using 32 bit values but it's not in PHP.

The biggest problem is that I get from remote server big integer 9223372036854775808(10) as hexadecimal 8000000000000000(16).

There is no chance to enable php_gmp (extension) on production server but I have to check selected bits in received value. Both, production and development server are 32bits machines.

Foi útil?

Solução

You can accomplish this using BC Math (Arbitrary Precision Mathematics):

BC Math allows you to perform mathematic operations on numbers. The difference between using arithmetic operators and using BC Maths is that instead of storing the number as an integer or a float, BC Math returns the number as string.

http://php.net/manual/en/ref.bc.php

PHP has to be compiled with BC Math; however most PHP installs should have this.

Unfortunately you can't do bitwise operations on strings, and BC Math doesn't have any built-in bitwise functions. However; after doing a bit of Googling, I found the following code sample and I've copied and pasted it here below:

function bitValue($no) { return bcpow(2, $no); }
function bitSet($no, $value) {
    $tmp = bcmod($value, bitValue($no+1));
    return bccomp(bcsub($tmp, bitValue($no)), 0)>= 0;
}

echo bitSet(49, bitValue(48)) ."\n";
echo bitSet(48, bitValue(48)) ."\n";
echo bitSet(47, bitValue(48)) ."\n";

(Credits to hernst42)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top