Mail Archives: djgpp/1999/08/23/09:48:49
On Sat, 21 Aug 1999 09:43:53 +0700, Batchex <thedark1 AT Phreaker DOT net>
wrote:
>I've tried this approach, but it will only gives the correct bit count
>if value is as high as 15. Higher than 15 (16 and higher) will give
>incorrect bit count. I've tried 8 bit values and go as far as 16 bit
>sequences.
Look, the algorithm is correct; you only really need to read my
description carefully to see how it works. Nevertheless, I've gone to
the trouble of actually implementing it (albeit in a very inefficient
manner), and the source code follows. It works perfectly for all
32-bit or less numbers.
--- (begin) ----
/* bit count program */
#include <stdio.h>
#include <stdlib.h>
unsigned long binstrtoval(const char *binstr)
{
unsigned long val = 0;
while( *binstr != '\0' ) {
val <<= 1;
if( *binstr == '1' ) val |= 1;
binstr++;
} /* end-while */
return val;
}
main()
{
char number[20];
unsigned long val, tempval;
unsigned long masked1, masked2, bmask1, bmask2;
printf( "Enter a binary number: " ); fflush(stdout);
fgets(number, 20, stdin);
val = binstrtoval(number); printf( "decimal value: %d\n", val );
bmask1 = binstrtoval("01010101010101010101010101010101");
bmask2 = bmask1 << 1;
masked1 = val & bmask1;
masked2 = (val & bmask2) >> 1;
tempval = masked1 + masked2;
bmask1 = binstrtoval("00110011001100110011001100110011");
bmask2 = bmask1 << 2;
masked1 = tempval & bmask1;
masked2 = (tempval & bmask2) >> 2;
tempval = masked1 + masked2;
bmask1 = binstrtoval("00001111000011110000111100001111");
bmask2 = bmask1 << 4;
masked1 = tempval & bmask1;
masked2 = (tempval & bmask2) >> 4;
tempval = masked1 + masked2;
bmask1 = binstrtoval("00000000111111110000000011111111");
bmask2 = bmask1 << 8;
masked1 = tempval & bmask1;
masked2 = (tempval & bmask2) >> 8;
tempval = masked1 + masked2;
bmask1 = binstrtoval("00000000000000001111111111111111");
bmask2 = bmask1 << 16;
masked1 = tempval & bmask1;
masked2 = (tempval & bmask2) >> 16;
tempval = masked1 + masked2;
printf( "\nNumber of bits set: %d\n", tempval );
}
__________________________________________________________
*** davmac - sharkin'!! davmac AT iname DOT com ***
my programming page: http://yoyo.cc.monash.edu.au/~davmac/
- Raw text -