-1

This is android code performs time calculation. Please see the below code:

int test1 = 1000*60*60*24*7; // milliseconds of the week
long test = test1*4;
Log.d(String.valueof(test));

the printed value is the minus value...

int test1 = 1000*60*60*24*7; // milliseconds of the week
long test3 = test1;
long test = test3*4;
Log.d(String.valueof(test));

the printed value is plus value.

Why are these values different?

drembert
  • 1,246
  • 1
  • 9
  • 18
user3217766
  • 69
  • 2
  • 8

2 Answers2

0

probably type coercion order. the first case is long = int * 4, the second is long = long * 4. The value is larger than the largest possible positive signed 32-bit integer, so the long = int * 4 must be getting run as long = (long)(int * 4). Explicitly casting to long before the multiplication should fix it: long = int * 4L;

try long test = (long)test1*4;

Andras
  • 2,995
  • 11
  • 17
0

1000*60*60*24*7 = 604,800,000

604,800,000 * 4 = 2,419,200,000

The maximum value for an int is 2.147,483,647 (the so-called Gangnam Number).

If you want to do this calculation, you have to do it in long so it does not overflow. At least before you start doing that last multiplication.

long test = test1*4;    // this is still an `int` multiplication

long test3 = test1;     // now it's `long`
long test = test3*4;

// or like this
long test = test1 * (long)4;

// or
long test = test1 * 4L;
Community
  • 1
  • 1
Thilo
  • 257,207
  • 101
  • 511
  • 656