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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With