Finding MSB in bit string
Guido van Rossum
guido at mcvax.uucp
Fri Nov 14 06:52:36 AEST 1986
In article <11053 at cca.UUCP> g-rh at cca.UUCP (Richard Harter) writes:
>Oh yes, what is the MSB of 0?
This should cause an exception like 1/0 does. If msb(x) is defined as
floor(2 log x), then it isn't defined for x==0.
>Here's another one -- suppose you want the number of 1's in a bit string.
>What's a good general method? How would a real programmer do it?
This has been discussed in this group a while ago. It goes something like
return count[x&0xff] + count[(x>>8)&0xff] +
count[(x>>16)&0xff] + count[(x>>32)&0xff;
where count is a 256-byte array of precomputed values. Of course you
could use a smaller array and add more values, possibly in a loop.
(I hope this time I didn't forget some offsets like in my solution of
the MSB problem.)
More information about the Comp.lang.c
mailing list