[courses] [C] Finally get lesson 10 exc #2 (without understanding your bit-shift)
Morgon Kanter
admin at surgo.net
Tue Nov 12 19:11:19 EST 2002
Ok, here it is, a few comments are omitted, I have commented KWMelvin's bit
shift thingie that was on converter she included with lesson 10.
/* begin exercise2.c */
#include <stdio.h>
#define BITS 32
int main() {
char line[10];
int x;
unsigned short int i, count = 0;
printf("Enter an integer number: ");
fgets(line, sizeof(line), stdin);
sscanf(line, "%i", &x);
/* Count all 1s in the integer, please explain what I even did! */
for(i = 0;i < BITS;i++) {
if( ((x & (1 << i)) >> i)) count++; /* DO NOT UNDERSTAND THIS PART!
* I copied it out of that one program attached to Lesson 10.
* I know what it does, (cycles through the bits one at a time,
* depending on i), but not how it does it. An explanation
* would be great! */
}
i = BITS - count; /* Get all of the remaining 0s */
/* print all of the 1s, on the left side */
while(count > 0) {
if(count == BITS - 8 || count == BITS - 16 || count == BITS - 24)
/* Is there an easier way to do that line above? */
printf(" ");
}
printf("1");
count--;
}
/* print the remaining 0s */
while(i > 0) {
if(i == BITS - 8 || i == BITS - 16 || i == BITS - 24) {
/* Is there an easier way to do the line above? */
printf(" ");
}
printf("0");
i--;
}
printf("\n");
return 0;
}
More information about the Courses
mailing list