Bell 32V development
[unix-history] / usr / lib / learn / C / L41.1a
#print
The problem is to produce a function
bitct(x)
which examines the bits in x, returning a count of
the number of 1-bits. There are various ways of doing
this job: here are two.
(1) a sane way. Shift the word x right 16 times (you are
on UNIX) and check the rightmost bit each time, counting
the number of times it is '1'.
(2) a machine-independent (sort of) way. The logical
bitwise AND of x and x-1 contains one fewer one bit than x itself.
Loop anding x and x-1 until you get zero.
Program either algorithm. Compile and test it. Leave it on
a file bitct.c and type "ready".
#once #create tzaqc.c
main()
{
int x;
x=23069;
if (bitct(x) != goodct(x)) return(1);
x=0;
if (bitct(x) != goodct(x)) return(1);
x=16384;
if (bitct(x) != goodct(x)) return(1);
x = -1;
if (bitct(x) != goodct(x)) return(1);
x= -200;
if (bitct(x) != goodct(x)) return(1);
return(0);
}
goodct(x)
{
int k, i;
for(k=i=0; i<16; i++)
{
k =+ (x&1);
x= x>>1;
}
return(k);
}
#user
cc tzaqc.c bitct.o
a.out
#succeed
/* a possible solution */
bitct(x)
{
int k, i;
for(i=k=0; i<16; i++) {
if (x&1)
k++;
x >>= 1;
}
return(k);
}
/* by the way, if you really care about
this problem a table lookup by whole bytes
is faster */
#log
#next
42.1a 10