Created
October 28, 2013 20:12
-
-
Save AnthonyDiGirolamo/7203745 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#define BYTETOBINARYPATTERN "%d%d%d%d%d%d%d%d" | |
#define BYTETOBINARY(byte) \ | |
(byte & 0x80 ? 1 : 0), \ | |
(byte & 0x40 ? 1 : 0), \ | |
(byte & 0x20 ? 1 : 0), \ | |
(byte & 0x10 ? 1 : 0), \ | |
(byte & 0x08 ? 1 : 0), \ | |
(byte & 0x04 ? 1 : 0), \ | |
(byte & 0x02 ? 1 : 0), \ | |
(byte & 0x01 ? 1 : 0) | |
void print_16_bits(unsigned int n) { | |
printf("%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d", | |
(n & 0x08000 ? 1 : 0), \ | |
(n & 0x04000 ? 1 : 0), \ | |
(n & 0x02000 ? 1 : 0), \ | |
(n & 0x01000 ? 1 : 0), \ | |
(n & 0x0800 ? 1 : 0), \ | |
(n & 0x0400 ? 1 : 0), \ | |
(n & 0x0200 ? 1 : 0), \ | |
(n & 0x0100 ? 1 : 0), \ | |
(n & 0x080 ? 1 : 0), \ | |
(n & 0x040 ? 1 : 0), \ | |
(n & 0x020 ? 1 : 0), \ | |
(n & 0x010 ? 1 : 0), \ | |
(n & 0x08 ? 1 : 0), \ | |
(n & 0x04 ? 1 : 0), \ | |
(n & 0x02 ? 1 : 0), \ | |
(n & 0x01 ? 1 : 0)); | |
} | |
int main(int argc, const char *argv[]) | |
{ | |
unsigned int n = 92; | |
unsigned int v = n; // count the number of bits set in v | |
unsigned int c; // c accumulates the total bits set in v | |
for (c = 0; v; c++) | |
{ | |
printf("c: %d\n", c); | |
/* | |
printf("v: "BYTETOBINARYPATTERN""BYTETOBINARYPATTERN"\n", | |
BYTETOBINARY(v>>8), BYTETOBINARY(v)); | |
printf("v-1: "BYTETOBINARYPATTERN""BYTETOBINARYPATTERN"\n", | |
BYTETOBINARY((v-1)>>8), BYTETOBINARY(v-1)); | |
printf("v&(v-1): "BYTETOBINARYPATTERN""BYTETOBINARYPATTERN"\n\n", | |
BYTETOBINARY((v&(v-1))>>8), BYTETOBINARY(v&(v-1))); | |
*/ | |
printf("v: ") ; print_16_bits(v) ; printf("\n") ; | |
printf("v-1: ") ; print_16_bits(v-1) ; printf("\n") ; | |
printf("v&(v-1): ") ; print_16_bits(v&(v-1)) ; printf("\n") ; | |
v &= v - 1; // clear the least significant bit set | |
} | |
printf("There are %d ones and in %d.\n", c, n); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment