Skip site navigation (1) Skip section navigation (2)

Re: Bit count

From: Kenneth Marshall <ktm(at)rice(dot)edu>
To: Rikard Bosnjakovic <rikard(dot)bosnjakovic(at)gmail(dot)com>
Cc: Nathaniel Trellice <naptrel(at)yahoo(dot)co(dot)uk>, pgsql-novice(at)postgresql(dot)org
Subject: Re: Bit count
Date: 2009-11-24 18:23:02
Message-ID: 20091124182302.GF3237@it.is.rice.edu (view raw or flat)
Thread:
Lists: pgsql-novice
On Tue, Nov 24, 2009 at 07:18:00PM +0100, Rikard Bosnjakovic wrote:
> On Tue, Nov 24, 2009 at 16:47, Nathaniel Trellice <naptrel(at)yahoo(dot)co(dot)uk> wrote:
> 
> [...]
> > If not, can anyone recommend the most efficient way within postgres to implement the kind of bit-counting tricks found at:
> 
> Perhaps something like this:
> 
> CREATE OR REPLACE FUNCTION bitcount(i integer) RETURNS integer AS $$
> DECLARE n integer;
> DECLARE amount integer;
>   BEGIN
>     amount := 0;
>     FOR n IN 1..16 LOOP
>       amount := amount + ((i >> (n-1)) & 1);
>     END LOOP;
>     RETURN amount;
>   END
> $$ LANGUAGE plpgsql;
> 
> 
> bos=# select bitcount(6);
>  bitcount
> ----------
>         2
> (1 row)
> 
> bos=# select bitcount(7);
>  bitcount
> ----------
>         3
> 
> bos=# select bitcount(4711);
>  bitcount
> ----------
>         7
> (1 row)
> 
> bos=# select bitcount(1024);
>  bitcount
> ----------
>         1
> (1 row)
> 
> 
> -- 
> - Rikard
> 

You could also setup a lookup table and just select the
bit count from the table. There was also a thread on how
to efficiently count the set bits that concluded with the
posting of a C function that could be used. It all depends
on your need for speed.

Regards,
Ken

In response to

pgsql-novice by date

Next:From: AaronDate: 2009-11-24 18:26:28
Subject: Internal time stamps?
Previous:From: Rikard BosnjakovicDate: 2009-11-24 18:18:00
Subject: Re: Bit count

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group