Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 768
user2632477 Avatar asked Dec 26 '22 23:12

user2632477


1 Answers

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
like image 174
Scotty Bauer Avatar answered Dec 29 '22 05:12

Scotty Bauer