How do I convert uint to int in C#?

Viewed 136961

How do I convert uint to int in C#?

8 Answers

Given:

 uint n = 3;

int i = checked((int)n); //throws OverflowException if n > Int32.MaxValue
int i = unchecked((int)n); //converts the bits only 
                           //i will be negative if n > Int32.MaxValue

int i = (int)n; //same behavior as unchecked

or

int i = Convert.ToInt32(n); //same behavior as checked

--EDIT

Included info as mentioned by Kenan E. K.

Take note of the checked and unchecked keywords.

It matters if you want the result truncated to the int or an exception raised if the result doesnt fit in signed 32 bits. The default is unchecked.

Convert.ToInt32() takes uint as a value.

uint i = 10;
int j = (int)i;

or

int k = Convert.ToInt32(i)

Assuming that the value contained in the uint can be represented in an int, then it is as simple as:

int val = (int) uval;

int intNumber = (int)uintNumber;

Depending on what kind of values you are expecting, you may want to check how big uintNumber is before doing the conversion. An int has a max value of about .5 of a uint.

Related