Thread: How to count ones in a bit string?
For example, I have a bit string as: B'101000000000000000000010' How do I count the number of ones in it? In this example, it is 3. Thanks, Cheng
There are probably fast better ways. But this is one way: postgres=> SELECT LENGTH( REPLACE( CAST( B'101000000000000000000010' AS TEXT ), '0', '')); length -------- 3 On Tue, Feb 21, 2012 at 7:32 AM, Cheng <niechenghust@gmail.com> wrote: > For example, I have a bit string as: > > B'101000000000000000000010' > > How do I count the number of ones in it? In this example, it is 3. > > Thanks, > Cheng > > -- > Sent via pgsql-novice mailing list (pgsql-novice@postgresql.org) > To make changes to your subscription: > http://www.postgresql.org/mailpref/pgsql-novice -- Regards, Richard Broersma Jr.
On 21 February 2012 17:44, Richard Broersma <richard.broersma@gmail.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@gmail.com>