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# ?
Remarks. The value of this constant is 2,147,483,647; that is, hexadecimal 0x7FFFFFFF.
Int32 is an immutable value type that represents signed integers with values that range from negative 2,147,483,648 (which is represented by the Int32. MinValue constant) through positive 2,147,483,647 (which is represented by the Int32. MaxValue constant. .
ToInt32() method to convert a specified value to a 32-bit signed integer. Let us take a double variable. double doubleNum = 11.53; Now, we will convert it to Int32 using the Convert.
The number 2,147,483,647 (or hexadecimal 7FFFFFFF16) is the maximum positive value for a 32-bit signed binary integer in computing.
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
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