How to avoid overflow of variable multiplication?

If I have the following code:

long interval = 0;
interval = ((6000 * 60) * 24) * 30;

It will not work, because I will need to make each literal long. So this will work:

interval = ((6000L * 60L) * 24L) * 30L;

But what if I try to propagate different variables of type char? Say I have:

char a, b, c, d;

And I give each of these characters a numerical value, so I try:

interval = a * b * c * d;

If this is an overflow, I cannot just put L because it will call different variables.

interval = aL * bL * cL * dL;

I tried to convert each of these characters long before the hand, but the product still returns a negative number.

+4
source share
3 answers

When applying a multiplicative operator to its operands,

In operands, a binary digital action is performed (§5.6.2).

, long, long.

, , , , long . . , . long

char a, b, c, d;
...
interval = 1L * a * b * c * d;
//        (......) result is a long value

, . , * long, *.

+1

() , long:

interval = (long)a * b * c * d;
+3
interval = ((6000L * 60L) * 24L) * 30L;

This code apparently calculates the number of milliseconds in 30 days.

So use what the JDK has to offer:

interval = TimeUnit.DAYS.toMillis(30L);

javadoc for TimeUnit

+2
source

Source: https://habr.com/ru/post/1569305/


All Articles