David
David

Reputation: 1830

Convert a long to an int cutting off the overflow

I want to cast a long value to an int value and if the long value is too big to fit into an int it should just be the the biggest possible int value. My solution looks like that:

long longVar = ...;
int intVar = (int) Math.min(longVar, Integer.MAX_VALUE)

In a more general way (to include the negative maximum) it would be:

long longVar = ...;
int intVar = (int) (longVar < 0 ? Math.max(longVar, Integer.MIN_VALUE) : Math.min(longVar, Integer.MAX_VALUE));

Is there an easier way to do this, like a method in the JRE or something?

Upvotes: 2

Views: 1367

Answers (3)

Leonardo Leoni
Leonardo Leoni

Reputation: 21

You can also write some reusable code.

package it.stackoverflow;

public class UtilInt {

    public static int getIntMaxMinLong(long longNumber){

        int intNumber = 0;

        if (longNumber < Integer.MIN_VALUE ) 
            intNumber = Integer.MIN_VALUE;

        else if (longNumber > Integer.MAX_VALUE)
            intNumber = Integer.MAX_VALUE;

        else 
            intNumber = (int) longNumber;

        return intNumber;
    }
}

You can call the method in the static way.

package it.stackoverflow;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int intNewValue = UtilInt.getIntMaxMinLong(224748223647L);

    }

}

Upvotes: 0

Fildor
Fildor

Reputation: 16104

An improvement would be

int intVar = (int) Math.min(Math.max(longVar, Integer.MIN_VALUE),
                            Integer.MAX_VALUE));

Math.max would make [Long.Min,Long.Max] => [Int.Min, Long.Max] and whatever outcome of that, if it is greater than Int.Max will be trimmed down by the outer Math.min to [Int.Min, Int.Max].

I don't know of a ready-to-go method doing this included in java.

The java 8 method Math.toIntExact will throw an exception on overflow. And using that to do this - well, I'd consider it a misuse of exceptions. And probably less efficient than above construct.

Upvotes: 1

Klitos Kyriacou
Klitos Kyriacou

Reputation: 11621

If you can use Guava, there is a method that does exactly what you want: static int Ints.saturatedCast(long):

long longVar = ...;
int intVar = Ints.saturatedCast(longVar);

For general interest, there's the Wikipedia article on saturation arithmetic. The Intel MMX instruction set uses saturation arithmetic and I think Intel offer an SDK to allow Java developers to use MMX. I'm not sure if Guava implements its methods using this SDK (probably not).

Upvotes: 0

Related Questions