Re: count the number of bits set to 1 in a bit string field

From: Ragnar <gnari(at)hive(dot)is>
To: Rajarshi Guha <rguha(at)indiana(dot)edu>
Cc: pgsql-general <pgsql-general(at)postgresql(dot)org>
Subject: Re: count the number of bits set to 1 in a bit string field
Date: 2007-07-15 23:20:09
Message-ID: 1184541609.5778.159.camel@localhost.localdomain
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On sun, 2007-07-15 at 15:35 -0400, Rajarshi Guha wrote:
> Hi, is there a built in function that will give me the number of bits
> that are set to 1 in a bit string field?

no, but it should be trivial to do with pl/pgsql

a naive implementation could be:

create or replace function bitsetlen(bit) returns int as $$
declare i int;
c int;
begin
c:=0;
for i in 1..length($1) loop
if substring($1,i,1)=B'1' then
c:=c+1;
end if;
end loop;
return c;
end;
$$ language plpgsql;

gnari

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2007-07-16 00:13:30 Re: Could not create log file error?
Previous Message novnov 2007-07-15 22:29:45 Re: Could not create log file error?