I am trying to get this to read a files integers and print the number of 1 bits in each integer. The file I am redirecting as input to test with has 100 in it. But the output I'm getting is:
Number of bits set to 1 in 49 = 3
Number of bits set to 1 in 48 = 2
Number of bits set to 1 in 48 = 2
Number of bits set to 1 in 10 = 2
I'd like to be getting Number of bits set to 1 in 100 = 3
Not sure if the while loop is correctly coded or what, can you help out?
Code:#include <stdio.h> #define EOF (-1) unsigned char bitcount(unsigned char); main() { int i; unsigned char count, i8; while ((i = getchar() ) != EOF) { if ((i < 0) || (i > 255)) { printf("Number out of range = %d\n", i); exit(1); } else { i8 = (unsigned char) i; count = bitcount(i8); printf("\n\nNumber of bits set to 1 in %d = %d\n",i,count); }//end else } //end while } //end main /* bitcount: count 1 bits in x */ unsigned char bitcount(unsigned char x) { unsigned char count; for (count = 0; x != 0; x >>=1) if (x & 01) count++; return count; }