Re: Bit count

From: Nathaniel Trellice <naptrel(at)yahoo(dot)co(dot)uk>
To: pgsql-novice(at)postgresql(dot)org
Subject: Re: Bit count
Date: 2009-11-26 14:27:20
Message-ID: 695983.71673.qm@web25007.mail.ukl.yahoo.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

Thanks for all the replies.

I'm giving this a spin, at present. It's based on Rikard's suggestion of using plpgsql script function. Like Jason and other have said, it could be done in a C function (and this was my first inclination), but the hassle of worrying about linking libraries, 32/64-bit installation etc is probably overkill. So this implementation of the 'MIT Hakmem' algorithm seemed like a good compromise between efficiency and efficacy:

CREATE FUNCTION mybitcount(n int4) RETURNS int4 AS $$
DECLARE tmp int4;
BEGIN
tmp = n - ((n >> 1) & 3681400539) - ((n >> 2) & 1227133513);
RETURN ((tmp + (tmp >> 3)) & 3340530119) % 63;
END
$$ LANGUAGE plpgsql IMMUTABLE STRICT;

Nathaniel

In response to

Browse pgsql-novice by date

  From Date Subject
Next Message Jean-Yves F. Barbier 2009-11-26 14:44:58 bytea and text
Previous Message Jasen Betts 2009-11-26 11:04:21 Re: Bit count