Re: How to count ones in a bit string?

From: Michael Wood <esiotrot(at)gmail(dot)com>
To: Richard Broersma <richard(dot)broersma(at)gmail(dot)com>
Cc: Cheng <niechenghust(at)gmail(dot)com>, pgsql-novice(at)postgresql(dot)org
Subject: Re: How to count ones in a bit string?
Date: 2012-02-21 15:52:12
Message-ID: CAP6d-HXbsJ-2rQDT2AU+ooLd-jrL1cvHpOJYJ92jMYUyqJvFpQ@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

On 21 February 2012 17:44, Richard Broersma <richard(dot)broersma(at)gmail(dot)com> wrote:
> There are probably fast better ways. But this is one way:
>
> postgres=> SELECT LENGTH( REPLACE( CAST( B'101000000000000000000010'
> AS TEXT ), '0', ''));
>  length
> --------
>      3

That seems like a good way to do it, unless you need to do this on a
lot of data and need it to be very fast or something.

If so, then maybe have a look at this:

http://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation

and maybe even this:

http://en.wikipedia.org/wiki/Hamming_weight#Processor_support

and implement it as a user defined function in C.

--
Michael Wood <esiotrot(at)gmail(dot)com>

In response to

Browse pgsql-novice by date

  From Date Subject
Next Message Matthias Leopold 2012-02-21 16:44:17 return values from plperl function
Previous Message Richard Broersma 2012-02-21 15:44:22 Re: How to count ones in a bit string?