简体   繁体   中英

java - Want to divide long (huge file size in TBs) by some number (huge int) and safely get an int

I want to divide long (huge file size in TBs) by some number (huge int) and safely get an int. But with the type conversion properties both int becomes long and the result is long. I'm sure my quotient will be an int, is casting ok or please direct me to a better solution.

Well if casting is okay, then just cast!

long size = ...;
int divisor = ...;
int result = (int) (size / divisor);

Of course you should only do this if you're sure that the result will genuinely be in the range of an int - you could always check that of course:

long size = ...;
int divisor = ...;
long fullResult = size / divisor;
if (fullResult < Integer.MIN_VALUE || fullResult > Integer.MAX_VALUE) {
    // Whatever, e.g. throw an exception
}
int result = (int) fullResult;

Use an explicit downcast:

long l_quot=l_size/(long)i_divisor;
int i_qout=(int)l_quot;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM