Re: count the number of bits set to 1 in a bit string field - Mailing list pgsql-general

From Ragnar
Subject Re: count the number of bits set to 1 in a bit string field
Date
Msg-id 1184541609.5778.159.camel@localhost.localdomain
Whole thread Raw
In response to count the number of bits set to 1 in a bit string field  (Rajarshi Guha <rguha@indiana.edu>)
Responses Re: count the number of bits set to 1 in a bit string field
List 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



pgsql-general by date:

Previous
From: novnov
Date:
Subject: Re: Could not create log file error?
Next
From: Stefan Becker
Date:
Subject: Re: count the number of bits set to 1 in a bit string field