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

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 (view raw or flat)
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

pgsql-novice by date

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

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