Re: Bit count

From: Rikard Bosnjakovic <rikard(dot)bosnjakovic(at)gmail(dot)com>
To: Nathaniel Trellice <naptrel(at)yahoo(dot)co(dot)uk>
Cc: pgsql-novice(at)postgresql(dot)org
Subject: Re: Bit count
Date: 2009-11-24 18:18:00
Message-ID: d9e88eaf0911241018p7b95bdaaqc65717bb6b663a60@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

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

In response to

  • Bit count at 2009-11-24 15:47:05 from Nathaniel Trellice

Responses

Browse pgsql-novice by date

  From Date Subject
Next Message Kenneth Marshall 2009-11-24 18:23:02 Re: Bit count
Previous Message Richard Broersma 2009-11-24 17:31:03 Re: PostgreSQL 8.4.1 and pljava