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

Re: Bit count

From: Josh Kupershmidt <schmiddy(at)gmail(dot)com>
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 19:14:51
Message-ID: 4ec1cf760911241114t2bcc9494x8079902702107019@mail.gmail.com (view raw or flat)
Thread:
Lists: pgsql-novice
On Tue, Nov 24, 2009 at 1:18 PM, Rikard Bosnjakovic
<rikard(dot)bosnjakovic(at)gmail(dot)com> 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;
>

[snip]
Clever! Here's a pure SQL version I whipped up.. perhaps there's a
more efficient pure SQL way that can avoid the string operations I'm
using :-)

# SELECT num, char_length(replace(num::bit(16)::text, '0', '')) AS
num_set_bits FROM numbers;
 num  | num_set_bits
------+--------------
    6     |            2
    7     |            3
 4711  |            7
 1024  |            1

Josh

In response to

pgsql-novice by date

Next:From: Tom LaneDate: 2009-11-24 19:24:51
Subject: Re: Internal time stamps?
Previous:From: Brian ModraDate: 2009-11-24 19:12:36
Subject: Re: Internal time stamps?

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