Reputation: 414
I want to covert a big number, which is bigger than int32 maximum range - to int32 using C#. So that if it is over than maximum range 2147483647, then it will start again from -2147483648. For now I am doing this like :
long val = 3903086636L;
long rem = val % 2147483648L;
long div = val / 2147483648L;
int result = div % 2 == 0 ? (int)rem - 1 : -2147483648 + (int)rem;
I am not sure that if I doing this correctly. Is there any utility function or quick way to doing this in C# ?
Upvotes: 5
Views: 219
Reputation: 37050
Why not simply add the rest to int.MinValue
:
long tmp = myValue - int.MaxValue;
while(tmp > int.MaxValue) tmp -= int.MaxValue;
if (tmp > 0) tmp = int.MinValue + tmp;
The loop preserves that you can work on numbers that are also greater then 2 * int.MaxValue
.
If you use this and test with myValue = 3 * int.MaxValue + 1
you will get 2147483647
as result.
Upvotes: 0
Reputation: 157048
If you don't have checked mode enabled, just casting it will handle the overflow as you expect:
int i = (int)val;
Or, as suggested by Matthew Watson, to make it compiler-setting independent:
int i = unchecked((int)val);
This will not throw an exception. The integer will overflow and continue counting from int.MinValue
.
Proof:
long val = (long)int.MaxValue + 1;
int result = (int)val;
Console.WriteLine(result == int.MinValue); // true
Upvotes: 5