I was attempting some basic programming in C using different integer types. The problem is to determine the number of ones in a given binary number. I used uint8_t as the type of the number and used a logical comparison with a left-shift operator. However, the comparisons don't work as expected:
My code is as follows:
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
int main()
{
uint8_t x=0xAA; //declare the number
uint8_t cnt=0, y; // Initialize other variables
while(x>0){
y=x<<1;
if(x > x<<1){
cnt++;
}
x = x<<1;
printf("%u %u \n", x, cnt);
}
printf("%u\n",cnt);
}
However, cnt is not updated at all: Output
However, if I typecast x<<1 to (uint8_t)(x<<1), or use y instead in the comparison, the code works. Could anyone explain this behavior? I am using the gcc compiler.
Thanks in advance