Convert Int32.Maximum + value to int32

I want to hide a large number that is larger than the maximum range of int32 - up to int32 using C #. So if it exceeds the maximum range of 2147483647, it will start again from -2147483648. So far I am doing this as:

long val = 3903086636L; long rem = val % 2147483648L; long div = val / 2147483648L; int result = div % 2 == 0 ? (int)rem - 1 : -2147483648 + (int)rem; 

I'm not sure if I do it right. Is there any utility feature or quick way to do this in C #?

+5
source share
2 answers

If you don’t have the established mode , just throwing it will handle the overflow, as you would expect:

 int i = (int)val; 

Or, as Matthew Watson suggested, make it independent of the compiler:

 int i = unchecked((int)val); 

This will not raise an exception. The integer will overflow and continue counting from int.MinValue .

Evidence:

 long val = (long)int.MaxValue + 1; int result = (int)val; Console.WriteLine(result == int.MinValue); // true 
+5
source

Why not just 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 saves that you can work with numbers that are also greater than 2 * int.MaxValue .

If you use this and test with myValue = 3 * int.MaxValue + 1 , you will get the result 2147483647 .

0
source

Source: https://habr.com/ru/post/1246384/


All Articles