home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: sci.math.num-analysis
- Path: sparky!uunet!infonode!ingr!analog!suhana!aaronb
- From: aaronb@suhana.analog.ingr.com (Aaron B.)
- Subject: Algorithm to find which bits set.
- Message-ID: <1992Jul26.013041.10387@infonode.ingr.com>
- Keywords: Bit counting
- Sender: harun@suhana (Aaron B.)
- Reply-To: aaronb@suhana.analog.ingr.com
- Organization: Home Office Enterprise
- Date: Sun, 26 Jul 1992 01:30:41 GMT
- Lines: 56
-
- Hi there:
-
- My friend asked me the fastest way of finding which bits are
- set in a bit-string. I gave him my first response. But I think there
- is a better way of doing it.
-
- If anybody have a better way of doing this please E-mail me your response.
-
- Thanks in advance.
-
- Aaron Bustamam
-
- aaronb@suhana.analog.ingr.com
-
- Here is my response:
-
- static unsigned char binvalue[9]={0x00, 0x01, 0x02, 0x04, 0x08,
- 0x10, 0x20, 0x40, 0x80 };
-
-
- /* Main function that will take any byte and display the bits position
- turn on. off is the offset of the byte in the bit-string.
- */
-
-
- int
- show_msb(ch, off)
- unsigned char ch;
- long off;
- {
- int pos;
-
- if ( ch )
- {
- pos = ilog2( ch );
- printf("position = %d\n",pos+off);
- ch ^= binvalue[pos]; /* could also use: ch -= binvalue[pos]; */
- show_msb(ch, off); /* recursive call for rest of bits */
- }
- return( 0 );
- }
-
- int
- ilog2(n)
- register unsigned char n;
- {
- register long q;
-
- q = 0;
- while( n )
- {
- n >>= 1;
- q++;
- }
- return( q );
- } /* ilog2 */
-