diff options
author | Adam Carpenter <gitlab@53hor.net> | 2019-07-23 12:09:24 -0400 |
---|---|---|
committer | Adam Carpenter <gitlab@53hor.net> | 2019-07-23 12:09:24 -0400 |
commit | 552bc70b77d4fca54929b46190128721b93d887c (patch) | |
tree | 2793d5aff4fce6b27e1056f89b09b52d41134a4b /ch2/2-9.c | |
parent | e41bafc5885aac630b6d19893e9c80cc334497c2 (diff) | |
download | learning-c-552bc70b77d4fca54929b46190128721b93d887c.tar.xz learning-c-552bc70b77d4fca54929b46190128721b93d887c.zip |
Cleaned up directory.
Diffstat (limited to 'ch2/2-9.c')
-rw-r--r-- | ch2/2-9.c | 40 |
1 files changed, 0 insertions, 40 deletions
diff --git a/ch2/2-9.c b/ch2/2-9.c deleted file mode 100644 index 5ab3241..0000000 --- a/ch2/2-9.c +++ /dev/null @@ -1,40 +0,0 @@ -#include <stdio.h> - -int bitcount_original(unsigned x); -int bitcount(unsigned x); - -int main() { - printf("%d\n", bitcount_original(0xaa)); - printf("%d\n", bitcount(0xaa)); - return 0; -} - -/* - * A binary subtraction operation will toggle the least-significant bits - * required for the subtraction. The `&` operation between two opposing bits - * will always result in 0. This is why using `x &= (x - 1)` will always delete - * the rightmost 1-bit in x; the least-significant 1-bit and all 1-bits - * generated from the subtraction operation will be zeroed out. - * - * This observation makes this implementation more efficient than - * `bitcount_original` simply because it requires fewer operations. - */ -int bitcount(unsigned x) { - int b; - - for (b = 0; x > 0; b++) - x &= (x - 1); - - return b; -} - -int bitcount_original(unsigned x) { - int b; - - for (b = 0; x != 0; x >>= 1) - if (x & 01) - b++; - - return b; -} - |