Path: news.mathworks.com!newsfeed-00.mathworks.com!nlpi057.nbdc.sbc.com!prodigy.net!news.glorb.com!news.aset.psu.edu!support1.mathforum.org!not-for-mail
From: bogfrog <jmcgraw@rcn.com>
Newsgroups: comp.soft-sys.matlab
Subject: Re: count number of
Date: Wed, 30 Jul 2008 14:36:50 EDT
Organization: The Math Forum
Lines: 34
Message-ID: <9740892.1217443041429.JavaMail.jakarta@nitrogen.mathforum.org>
References: <g6q9kq$log$1@fred.mathworks.com>
NNTP-Posting-Host: nitrogen.mathforum.org
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
X-Trace: support1.mathforum.org 1217443041 28726 144.118.30.135 (30 Jul 2008 18:37:21 GMT)
X-Complaints-To: news@support1.mathforum.org
NNTP-Posting-Date: Wed, 30 Jul 2008 18:37:21 +0000 (UTC)
Xref: news.mathworks.com comp.soft-sys.matlab:482720



> Gonna share??


Sure.  But it's optimized for a sparse number of 1's.  It's just based on some c-code I found online.  It's still not as fast as I'd _really_ like, but here is the source:

---------------------------------
#include "mex.h"

void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[]) {
    
    unsigned int n, c;
    
/* check: only one input and one output argument */
    if (nrhs !=1)
        mexErrMsgTxt("Must have one input argument");
    if (nlhs !=1)
        mexErrMsgTxt("Must have one output argument");
    
    n = mxGetScalar(prhs[0]);
    
    c = 0;
    while (n)   {
        c++ ;
        n &= (n - 1) ;
    }
    plhs[0]=mxCreateDoubleMatrix(1,1,mxREAL);
    *mxGetPr(plhs[0])=c; 
}
--------------------------------------

If you name it bitcount_c.c, just do "mex bitcount_c.c" at the command line and use it as so:

numbits = bitcount_c(number)