4

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);
jasonsirota
  • 4,003
  • 3
  • 17
  • 15
  • The operator name was edited from "modulus" to "modulo". Although it seems modulo is the correct name: http://en.wikipedia.org/wiki/Modulo_operation however, MSDN has it as "modulus" http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx I think MSDN might be wrong? – jasonsirota Feb 18 '11 at 18:35

3 Answers3

4

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.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • The hardware division instruction on the x86 accepts a 64-bit dividend and 32-bit divisor, and produces a 32-bit quotient and 32-bit remainder. If the divisor is only 32 bits but the quotient could exceed 32 bits, then it may be necessary to use a compare instruction to split the division in case it would overflow, or else split the division unconditionally. Note that promoting the dividend to 32 bits will require extra code unless the JIT realizes that it can't actually hold a value that won't fit in 32 bits. – supercat Nov 18 '14 at 22:20
1

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.

invalidsyntax
  • 640
  • 1
  • 5
  • 14
0

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.

JAiro
  • 5,914
  • 2
  • 22
  • 21