What's the most idiomatic way in Java to verify that a cast from long
to int
does not lose any information?
This is my current implementation:
public static int safeLongToInt(long l) {
int i = (int)l;
if ((long)i != l) {
throw new IllegalArgumentException(l + " cannot be cast to int without changing its value.");
}
return i;
}
here is a solution, in case you don't care about value in case it is bigger then needed ;)
One other solution can be:
I have tried this for cases where the client is doing a POST and the server DB understands only Integers while the client has a Long.
With BigDecimal:
With Google Guava's Ints class, your method can be changed to:
From the linked docs:
Incidentally, you don't need the
safeLongToInt
wrapper, unless you want to leave it in place for changing out the functionality without extensive refactoring of course.Java integer types are represented as signed. With an input between 231 and 232 (or -231 and -232) the cast would succeed but your test would fail.
What to check for is whether all of the high bits of the
long
are all the same:I think I'd do it as simply as:
I think that expresses the intent more clearly than the repeated casting... but it's somewhat subjective.
Note of potential interest - in C# it would just be: