0

I'm trying to make an AND operation between 2 Bigints and then to count the number of bits 1 on binary representation.

Example :

$a and $b are bigints resulting of a MySql query.

$result = countones($a & $b);

with :

function countones($n){
  $c =0;
  while($n){
    $c += $n&1;
    $n = $n>>1;
  }
  return $c;
}

With Ints no problem. I've tried to use gmp functions but my attemps failed... I must be missing something...

  • possible duplicate of [How to fastest count the number of set bits in php?](http://stackoverflow.com/questions/16848931/how-to-fastest-count-the-number-of-set-bits-in-php) – Jérôme Teisseire Feb 01 '14 at 22:33

1 Answers1

0

You can just CAST them as strings in SQL and then change $n&1 to substr($n,-1)&1 and $n >>= 1; to $n = substr($n,0,-1);.

Janus Troelsen
  • 20,267
  • 14
  • 135
  • 196
  • Thank you. Yes, at first I was thinking to do such thing but this operation must be done in a loop thousands of times, and I think that using bitwise will be much faster... if it is possible to do it with Bigints as well :-/ – user3261521 Feb 01 '14 at 23:10
  • it is not possible since PHP doesn't have any built-in bigints which means that your database library would rely on functionality that isn't always there... – Janus Troelsen Feb 01 '14 at 23:58
  • You are right, and it is useless to want to deal with BigInts as PHP is not ready for it. Instead I decided to use 2 fields Int (for performance reasons). The code was a bit longer, but is robust, and it works. Thanks again for your help. – user3261521 Feb 08 '14 at 17:56
  • This if course only works if the bigint isn't of unlimited size. But I guess it's usually not like that in SQL implementations even if bigint isn't part of the standard. – Janus Troelsen Feb 12 '14 at 10:32