1994-07-07 - Re: Counting bits

Header Data

From: rarachel@prism.poly.edu (Arsen Ray Arachelian)
To: rishab@dxm.ernet.in
Message Hash: c10cf447154aaf3d78c10f853088fc4717c8f169bcb631fc5325e7caf38edf57
Message ID: <9407070147.AA11105@prism.poly.edu>
Reply To: <gate.Pk12oc1w165w@dxm.ernet.in>
UTC Datetime: 1994-07-07 01:59:57 UTC
Raw Date: Wed, 6 Jul 94 18:59:57 PDT

Raw message

From: rarachel@prism.poly.edu (Arsen Ray Arachelian)
Date: Wed, 6 Jul 94 18:59:57 PDT
To: rishab@dxm.ernet.in
Subject: Re: Counting bits
In-Reply-To: <gate.Pk12oc1w165w@dxm.ernet.in>
Message-ID: <9407070147.AA11105@prism.poly.edu>
MIME-Version: 1.0
Content-Type: text

Why bother when you can simply do an eight line function?

int bitcount(char b)
register int retval=0;

 if (a & 1) retval++;
 if (a & 2) retval++;
 if (a & 4) retval++;
 if (a & 8) retval++;
 if (a & 16) retval++;
 if (a & 32) retval++;
 if (a & 64) retval++;
 if (a & 128) retval++; 

return retval;

This function, (if you have a decent compiler) will be turned into about 32
instructions at most.  IE:
  MOV BL,00
  MOV AL,value_of_a_wherever_that_may_be_in_the_stack
  AND AL,01
  JZ @+2_instructions
  AND AL,02
  JZ @+2_instructions...
  ad compiler nausea.

Simple, no shifting, no adding, no dividing, and best of all, it's straight
forward, and you don't have the possibility of sneaking in bugs.  Whereas
the previous example is a one liner, and may be shorter, it will be far
harder for humans to understand. :-)

Just my two bits. ;^)