Re: Bit count - Mailing list pgsql-novice

From Nathaniel Trellice
Subject Re: Bit count
Date
Msg-id 695983.71673.qm@web25007.mail.ukl.yahoo.com
Whole thread Raw
In response to Re: Bit count  (Rikard Bosnjakovic <rikard.bosnjakovic@gmail.com>)
List 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
otherhave said, it could be done in a C function (and this was my first inclination), but the hassle of worrying about
linkinglibraries, 32/64-bit installation etc is probably overkill. So this implementation of the 'MIT Hakmem' algorithm
seemedlike 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




pgsql-novice by date:

Previous
From: Jasen Betts
Date:
Subject: Re: Bit count
Next
From: "Jean-Yves F. Barbier"
Date:
Subject: bytea and text