System.Convert.ToInt32 Method

Converts the string representation of a number in a specified base to an equivalent 32-bit signed integer.

Syntax

public static int ToInt32 (string value, int fromBase)

Parameters

value
A string that contains the number to convert.
fromBase
The base of the number in value, which must be 2, 8, 10, or 16.

Returns

A 32-bit signed integer that is equivalent to the number in value, or 0 (zero) if value is null.

Remarks

If fromBase is 16, you can prefix the number specified by the value parameter with "0x" or "0X".

Because the negative sign is not supported for non-base 10 numeric representations, the Convert.ToInt32(string, int) method assumes that negative numbers use two’s complement representation. In other words, the method always interprets the highest-order binary bit of an integer (bit 31) as its sign bit. As a result, it is possible to write code in which a non-base 10 number that is out of the range of the int data type is converted to an int value without the method throwing an exception. The following example increments int.MaxValue by one, converts the resulting number to its hexadecimal string representation, and then calls the Convert.ToInt32(string, int) method. Instead of throwing an exception, the method displays the message, "0x80000000 converts to -2147483648."

code reference: System.Convert.BaseConversion#1

When performing binary operations or numeric conversions, it is always the responsibility of the developer to verify that a method is using the appropriate numeric representation to interpret a particular value. As the following example illustrates, you can ensure that the method handles overflows appropriately by first retrieving the sign of the numeric value before converting it to its hexadecimal string representation. Throw an exception if the original value was positive but the conversion back to an integer yields a negative value.

code reference: System.Convert.BaseConversion#2

Requirements

Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0, 4.0.0.0