Question: I'm working on a coding project where I write a C program that counts the number of 1s in the binary representation of an unsigned
I'm working on a coding project where I write a C program that counts the number of 1s in the binary representation of an unsigned integer value (4 bytes). For example, given a 254 integer value, my C program should print 7 on the screen. The program should take an unsigned integer number from user as a command line input, check whether it is a valid integer number (i.e., 0 ~ 2^32-1), and count 1s in the binary representation of that number. If an input integer is invalid then the program should print a warning message and stop. We're to assume that all inputs will be regular unsigned integers; no floating points, decimals, or weird things like 2abc. But I'm wondering if I've done something wrong. Let me explain. Here is my code:
int main() {
unsigned int num; int count = 0;
printf("Please enter an integer: "); scanf("%u", &num);
if (0 <= num <= 0xffffffff) {
while (num > 0) {
count += num & 1;
num >>= 1;
}
printf("%u ", count);
} else {
printf("Warning: this is not a valid integer.");
}
return 0; }
I'm not sure what this means, but at any rate, the program compiles. When I enter a negative number, I get weird values when negative numbers should trigger my else statement, as they aren't valid integers. What have I done wrong?
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
