Search code examples
c++cbit-shiftunsigned

bit shift for unsigned int, why negative?


Code:

unsigned int i = 1<<31;
printf("%d\n", i);

Why the out put is -2147483648, a negative value?


Updated question:

#include <stdio.h>

int main(int argc, char * argv[]) {
    int i = 1<<31;
    unsigned int j = 1<<31;
    printf("%u, %u\n", i, j);
    printf("%d, %d\n", i, j);

    return 0;
}

The above print:

2147483648, 2147483648
-2147483648, -2147483648

So, does this means, signed int & unsigned int have the same bit values, the difference is how you treat the 31st bit when convert it to a number value?


Solution

  • %d prints the int version of the unsigned int i. Try %u for unsigned int.

    printf("%u\n", i);
    

    int main(){
        printf("%d, %u",-1,-1);
        return 0;
    }
    

    Output: -1, 4294967295

    i.e The way a signed integer is stored and how it gets converted to signed from unsigned or vice-versa will help you. Follow this.

    To answer your updated question, its how the system represents them i.e in a 2's complement (as in the above case where -1 =2's complement of 1 = 4294967295.