0

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

SMajumder
  • 11
  • 2
  • Welcome, please don't post images, post a [Minimal Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) as text, the shortest *complete* code that shows what you have tried, by copy/pasting it, after you check it compiles and does exhibit the behaviour described. May I suggest you take the [Tour](https://stackoverflow.com/tour) and read [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) – Weather Vane Nov 19 '22 at 19:57
  • Hi there! Could you include the code in text instead of as a screenshot? This will make it easier for others to test your code and reproduce your results. See https://stackoverflow.com/editing-help#code for how to include code in your question. – eracer9 Nov 19 '22 at 19:59
  • Note that `(x << 1)` is an integer promotion, so `x > (x << 1)` will never be true. Whereas `y` has been truncated. – Weather Vane Nov 19 '22 at 20:00
  • Thanks, I have posted the code(s) as a minimum working example. – SMajumder Nov 20 '22 at 03:09
  • @WeatherVane, I checked your logic by printing them out and yes, it seems that such a promotion could be happening, as at times `(x<<1)` seems to go out of range for uint8_t. I don't understand why this type conversion could happen though. I am aware that unsigned and signed numbers should not be compared, but when do such integer promotions happen? Thanks. – SMajumder Nov 20 '22 at 03:16
  • Please see the link in the 'close' reason. – Weather Vane Nov 20 '22 at 06:17

0 Answers0