Computer Chess Club Archives


Search

Terms

Messages

Subject: Re: Counting Bits in BitBoard

Author: Dieter Buerssner

Date: 04:54:20 01/07/03

Go up one level in this thread


On January 07, 2003 at 03:22:02, Russell Reagan wrote:

>int PopCnt(register BITBOARD a) {
>  register int c=0;
>
>  while(a) {
>    c++;
>    a &= a - 1;
>  }
>  return(c);
>}

On architectures, that don't have native 64 bit words, the following will most
probably be significantly faster:

int PopCount(unsigned long long a)
{
  unsigned long w;
  int n = 0;
  w = a&0xffffffffUL;
  if (w)
    do
    {
      n++;
    }
    while ((w &= w-1) != 0);
  w = (a>>32)&0xffffffffUL;
  if (w)
    do
    {
      n++;
    }
    while ((w &= w-1) != 0);
  return n;
}

Note, that any slighly decent compiler will optimize the masks away, but they
make the code portable. It produces almost the same code, as the Crafty assembly
version, and possibly is even faster, when inlined (the bitboard may already be
in some register pair). Some unportable microoptimization can be added by using
a union or some (not Standard C) pointer casting tricks like

  w = *(((unsigned long *)&a)+1);

Although, the use of the adress operator may also confuse the optimizer.
For highly populated bitboard, other methods certainly will be faster. Perhaps,
other methods are allways faster ...

Regards,
Dieter



This page took 0 seconds to execute

Last modified: Thu, 15 Apr 21 08:11:13 -0700

Current Computer Chess Club Forums at Talkchess. This site by Sean Mintz.