C ා the instance method of converting uint value to int


Uint in C is an unsigned integer type, and int is a qualified integer type. The value range of the two is different, so how to convert uint value to int?

Open visual studio and create a console application. All the code in this paper is demonstrated in the main method of the program.cs file. First, check the maximum uint.maxvalue = 4294967295 and the minimum uint.minvalue = 0 of the uint unsigned integer type

Then in the main method, use int.maxvalue to get the maximum value of int, and int.minvalue to get the minimum value of int. From the running results, the maximum value int.maxvalue = 2147483647 and the minimum value int.minvalue = – 2147483648 of int signed integer type

As can be seen from the above two results, uint unsigned means that only integers have no negative numbers. Int signed means that there are both integers and negative numbers. In addition, uint’s positive range is twice as large as int’s

When uint value is in the range of int, only the format of (int) variable can be converted to int value. This is a cast, valid for numbers in range

When uint value is outside the range of positive int, data overflow will occur when using the format conversion of (int) variable, but the program will not report an error. The converted value is not the desired result

For the above situation, if the program encountered, but not reported an error, the problems will be very puzzling. It is absolutely unforgivable to assume that the bank deposits an extra dollar, which leads to a number overflow and turns into a negative number. Therefore, adding the checked keyword to the converted code will throw an exception when the conversion overflows to prevent overflow

In addition to using the cast of parenthesis int, you can also use the following methods to cast:

1) Int.parse cast. If it overflows, it will directly report an error and throw an exception

2) Int.tryparse conversion. If the data overflows, the conversion will return false, that is, the conversion fails without throwing an exception


The above is all about how to convert uint value into int in cා. Thank you for your reading and support for developepaer.