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

From: Stefan Becker <pgsql(at)yukonho(dot)de>
To: 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 21:02:35
Message-ID: 200707152302.35315.pgsql@yukonho.de
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Hi,

I don't quite know what you mean by a "bit string field" but for any
numeric, better integer row can use the following construct:

Say the bits you where testing where bit 3 ('00000100' bit),
and bit 6 ('00100000' bit) of say some_integer row....

then this would do it:

select
sum(case when (some_int & x'0004'::int)=0 then 0 else 1 end)
as count_of3thbit,
sum(case when (some_int & x'0020'::int)=0 then 0 else 1 end)
as count_of6thbit
from mytable ;

constant x'0004'::int = 4
constant x'0020'::int = 32

by best regards,

Stefan

Am Sonntag, 15. Juli 2007 21:35 schrieb Rajarshi Guha:
> 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?
>
> Thanks,
>
> -------------------------------------------------------------------
> Rajarshi Guha <rguha(at)indiana(dot)edu>
> GPG Fingerprint: 0CCA 8EE2 2EEB 25E2 AB04 06F7 1BB9 E634 9B87 56EE
> -------------------------------------------------------------------
> Without love intelligence is dangerous;
> without intelligence love is not enough.
> -- Ashley Montagu

--
email: stefan(at)yukonho(dot)de
tel : +49 (0)6232-497631
http://www.yukonho.de

In response to

Browse pgsql-general by date

  From Date Subject
Next Message novnov 2007-07-15 21:36:09 Could not create log file error?
Previous Message Rajarshi Guha 2007-07-15 19:35:55 count the number of bits set to 1 in a bit string field