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

Re: Efficiently determining the number of bits set in the contents of, a VARBIT field

From: TJ O'Donnell <tjo(at)acm(dot)org>
To: pgsql-sql(at)postgresql(dot)org, allank(at)sanbi(dot)ac(dot)za
Subject: Re: Efficiently determining the number of bits set in the contents of, a VARBIT field
Date: 2008-07-27 13:57:37
Message-ID: 488C7ED1.8050908@acm.org (view raw or flat)
Thread:
Lists: pgsql-sql
I use a c function, nbits_set that will do what you need.
I've posted the code in this email.

TJ O'Donnell
http://www.gnova.com

#include "postgres.h"
#include "utils/varbit.h"

Datum   nbits_set(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(nbits_set);
Datum
nbits_set(PG_FUNCTION_ARGS)
{
/* how many bits are set in a bitstring? */

         VarBit     *a = PG_GETARG_VARBIT_P(0);
         int n=0;
         int i;
         unsigned char *ap = VARBITS(a);
         unsigned char aval;
         for (i=0; i < VARBITBYTES(a); ++i) {
                 aval = *ap; ++ap;
                 if (aval == 0) continue;
                 if (aval & 1) ++n;
                 if (aval & 2) ++n;
                 if (aval & 4) ++n;
                 if (aval & 8) ++n;
                 if (aval & 16) ++n;
                 if (aval & 32) ++n;
                 if (aval & 64) ++n;
                 if (aval & 128) ++n;
         }
         PG_RETURN_INT32(n);
}



> Hi all,
> Am looking for a fast and efficient way to count the number of bits set 
> (to 1) in a VARBIT field. I am currently using 
> "LENGTH(REGEXP_REPLACE(CAST(a.somefield_bit_code AS TEXT),'0','','g'))".
> 
> Allan.


Responses

pgsql-sql by date

Next:From: Milan OparnicaDate: 2008-07-27 22:11:25
Subject: Re: PERSISTANT PREPARE (another point of view)
Previous:From: Giorgio ValotiDate: 2008-07-26 20:20:41
Subject: Re: Select default values

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