Search code examples
cunsigned-integerunsigned-long-long-int

unsigned int(32bit) to unsigned long long (64bit)


In the code below, I multiplied 0xffffffff by 2 for an unsigned int(32bit) and stored it in a unsigned long long(64bit). Why don't I get the actual output which is 8589934588. Instead I get 4294967294. Thanks in advance. OUTPUT: Sizeof i=4 Sizeof J=8 2xi=4294967292

/* Code starts here */
#include <stdio.h>
#include <stdlib.h>

int main (void) 
{
    unsigned int i=4294967294;
    unsigned long long j=i*2;
    printf("Sizeof i=%d\n", sizeof(i));
    printf("Sizeof J=%d\n", sizeof(j));
    printf("2xi=%llu\n", j);

    return 0;
}

Solution

  • It's because the i*2 is integer multiply. Even though you're storing it in a long long, you're still doing integer math, which causes an overflow.

    The following code works, as we promote it up to long long multiply

    #include <stdio.h>
    #include <stdlib.h>
    int main (void)
    {
      unsigned int i=4294967294;
      unsigned long long j=((unsigned long long)i)*2;
      printf("Sizeof i=%d\n", sizeof(i));
      printf("Sizeof J=%d\n", sizeof(j));
      printf("2xi=%llu\n", j);
    
      return 0;
    }
    

    Result:

    bash-4.1$ gcc long.c
    bash-4.1$ ./a.out
    Sizeof i=4
    Sizeof J=8
    2xi=8589934588