Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Int32.Maximum+ valued number to int32

Tags:

c#

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# ?

like image 275
Arnab Avatar asked Apr 04 '16 08:04

Arnab


People also ask

What is the maximum value for an Int32?

Remarks. The value of this constant is 2,147,483,647; that is, hexadecimal 0x7FFFFFFF.

How many values is Int32?

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. .

How do you use Convert to INT 32?

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.

What is the maximum value that can be stored in a 32-bit signed integer of C language?

The number 2,147,483,647 (or hexadecimal 7FFFFFFF16) is the maximum positive value for a 32-bit signed binary integer in computing.


1 Answers

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
like image 188
Patrick Hofman Avatar answered Nov 10 '22 01:11

Patrick Hofman