简体   繁体   中英

Why is a modulo operator (%) result implicitly cast to the left side rather than the right side in C#?

Take the following code:

long longInteger = 42;
int normalInteger = 23;
object rem = longInteger % normalInteger;

If rem is the remainder of longInteger / normalInteger , shouldn't the remainder always be bounded by the smaller sized "int", the divisor? Yet in C#, the above code results in rem being a long .

Is it safe to convert rem to int without any loss of data?

int remainder = Convert.ToInt32(rem);

There is no overload of the modulo operator that takes a long and an int , so the int will be converted to long to match the other operand.

Looking at it at a lower level, in the CPU there is no separate instruction for calculating modulo, it's just one of the results of the division operation. The output of the operation is the result of the division, and the reminder. Both are the same size, so as the result of the division has to be a long , so is the reminder.

As the reminder has to be smaller than the divisor, you can safely cast the result to int when the divisor comes from an int .

No matter what your two integers, the outcome must be lower than "normalInteger". Therefore, the result "rem" will be constrained to the limits of an int type. So, it will be safe to convert rem to int without loss of data.

yes it has not problem, the convert function is going to round the result. then you should know if it is usefull for you or not.

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