/count_bits.c Secret
Created
July 12, 2016 13:17
Revisions
-
ajaysusarla created this gist
Jul 12, 2016 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,27 @@ #include <stdint.h> #include <limits.h> #define numbits(x) (sizeof(x) * 8) #define max_signed_value_of_type(t) \ (INTMAX_MAX >> (numbits(intmax_t) - numbits(t))) void count_bits(unsigned int num) { size_t bits = numbits(num); unsigned int max = max_signed_value_of_type(num) + 1; int i; unsigned int t = num; int zeroes = 0, ones = 0; for (i = 0; i < bits; i++) { if (!!(num & max)) ones++; else zeroes++; num = num << 1; } printf("%u has %d 0's and %d 1's in its binary representation.\n", t, zeroes, ones); }