System.Int32 结构

本文提供了此 API 参考文档的补充说明。

Int32 是一个不可变值类型,表示有符号整数,其值范围为负 2,147,483,648(由 Int32.MinValue 常量表示)到正 2,147,483,647(由 Int32.MaxValue 常量表示)。 .NET 还包括无符号 32 位整数值类型, UInt32表示介于 0 到 4,294,967,295 的值。

实例化 Int32 值

可以通过多种方式实例化 Int32 值:

  • 可以声明变量 Int32 ,并为其分配数据类型范围内的 Int32 文本整数值。 以下示例声明两个 Int32 变量,并以此方式为其分配值。

    int number1 = 64301;
    int number2 = 25548612;
    
    let number1 = 64301
    let number2 = 25548612
    
    Dim number1 As Integer = 64301
    Dim number2 As Integer = 25548612
    
  • 可以分配其范围是该类型的子集的 Int32 整数类型的值。 这是一个扩大的转换,不需要 C# 中的强制转换运算符或 Visual Basic 中的转换方法,但确实需要 F# 中的转换。

    sbyte value1 = 124;
    short value2 = 1618;
    
    int number1 = value1;
    int number2 = value2;
    
    let value1 = 124y
    let value2 = 1618s
    
    let number1 = int value1
    let number2 = int value2
    
    Dim value1 As SByte = 124
    Dim value2 As Int16 = 1618
    
    Dim number1 As Integer = value1
    Dim number2 As Integer = value2
    
  • 可以分配其范围超过该 Int32 类型的数值类型的值。 这是一个缩小的转换,因此它需要 C# 或 F# 中的强制转换运算符,以及 Visual Basic 中的转换方法(如果 Option Strict 已启用)。 如果数值是包含SingleDouble小数部分的值,Decimal则其小数部分的处理取决于执行转换的编译器。 以下示例执行缩小转换,将多个数值 Int32 分配给变量。

    long lNumber = 163245617;
    try {
       int number1 = (int) lNumber;
       Console.WriteLine(number1);
    }
    catch (OverflowException) {
       Console.WriteLine("{0} is out of range of an Int32.", lNumber);
    }
    
    double dbl2 = 35901.997;
    try {
       int number2 = (int) dbl2;
       Console.WriteLine(number2);
    }
    catch (OverflowException) {
       Console.WriteLine("{0} is out of range of an Int32.", dbl2);
    }
    
    BigInteger bigNumber = 132451;
    try {
       int number3 = (int) bigNumber;
       Console.WriteLine(number3);
    }
    catch (OverflowException) {
       Console.WriteLine("{0} is out of range of an Int32.", bigNumber);
    }
    // The example displays the following output:
    //       163245617
    //       35902
    //       132451
    
    let lNumber = 163245617L
    try
        let number1 = int lNumber
        printfn $"{number1}"
    with :? OverflowException ->
        printfn "{lNumber} is out of range of an Int32."
    
    let dbl2 = 35901.997
    try
        let number2 = int dbl2
        printfn $"{number2}"
    with :? OverflowException ->
        printfn $"{dbl2} is out of range of an Int32."
    
    let bigNumber = BigInteger 132451
    try
        let number3 = int bigNumber
        printfn $"{number3}"
    with :? OverflowException ->
        printfn $"{bigNumber} is out of range of an Int32."
    
    // The example displays the following output:
    //       163245617
    //       35902
    //       132451
    
    Dim lNumber As Long = 163245617
    Try
       Dim number1 As Integer = CInt(lNumber)
       Console.WriteLine(number1)
    Catch e As OverflowException
       Console.WriteLine("{0} is out of range of an Int32.", lNumber)
    End Try
    
    Dim dbl2 As Double = 35901.997
    Try
       Dim number2 As Integer = CInt(dbl2)
       Console.WriteLine(number2)
    Catch e As OverflowException
       Console.WriteLine("{0} is out of range of an Int32.", dbl2)
    End Try
       
    Dim bigNumber As BigInteger = 132451
    Try
       Dim number3 As Integer = CInt(bigNumber)
       Console.WriteLine(number3)
    Catch e As OverflowException
       Console.WriteLine("{0} is out of range of an Int32.", bigNumber)
    End Try    
    ' The example displays the following output:
    '       163245617
    '       35902
    '       132451
    
  • 可以调用类的方法 Convert ,将任何受支持的类型转换为值 Int32 。 这是可能的,因为 Int32 支持 IConvertible 接口。 下面的示例演示了值数组 DecimalInt32 值的转换。

    decimal[] values= { Decimal.MinValue, -1034.23m, -12m, 0m, 147m,
                        199.55m, 9214.16m, Decimal.MaxValue };
    int result;
    
    foreach (decimal value in values)
    {
       try {
          result = Convert.ToInt32(value);
          Console.WriteLine("Converted the {0} value '{1}' to the {2} value {3}.",
                            value.GetType().Name, value,
                            result.GetType().Name, result);
       }
       catch (OverflowException) {
          Console.WriteLine("{0} is outside the range of the Int32 type.",
                            value);
       }
    }
    // The example displays the following output:
    //    -79228162514264337593543950335 is outside the range of the Int32 type.
    //    Converted the Decimal value '-1034.23' to the Int32 value -1034.
    //    Converted the Decimal value '-12' to the Int32 value -12.
    //    Converted the Decimal value '0' to the Int32 value 0.
    //    Converted the Decimal value '147' to the Int32 value 147.
    //    Converted the Decimal value '199.55' to the Int32 value 200.
    //    Converted the Decimal value '9214.16' to the Int32 value 9214.
    //    79228162514264337593543950335 is outside the range of the Int32 type.
    
    let values = 
        [| Decimal.MinValue; -1034.23M; -12m; 0M; 147M
           199.55M; 9214.16M; Decimal.MaxValue |]
    
    for value in values do
        try
            let result = Convert.ToInt32 value
            printfn $"Converted the {value.GetType().Name} value '{value}' to the {result.GetType().Name} value {result}."
            
        with :? OverflowException ->
            printfn $"{value} is outside the range of the Int32 type."
       
    // The example displays the following output:
    //    -79228162514264337593543950335 is outside the range of the Int32 type.
    //    Converted the Decimal value '-1034.23' to the Int32 value -1034.
    //    Converted the Decimal value '-12' to the Int32 value -12.
    //    Converted the Decimal value '0' to the Int32 value 0.
    //    Converted the Decimal value '147' to the Int32 value 147.
    //    Converted the Decimal value '199.55' to the Int32 value 200.
    //    Converted the Decimal value '9214.16' to the Int32 value 9214.
    //    79228162514264337593543950335 is outside the range of the Int32 type.
    
    Dim values() As Decimal = { Decimal.MinValue, -1034.23d, -12d, 0d, 147d, _
                                199.55d, 9214.16d, Decimal.MaxValue }
    Dim result As Integer
    
    For Each value As Decimal In values
       Try
          result = Convert.ToInt32(value)
          Console.WriteLine("Converted the {0} value '{1}' to the {2} value {3}.", _
                            value.GetType().Name, value, _
                            result.GetType().Name, result)
       Catch e As OverflowException
          Console.WriteLine("{0} is outside the range of the Int32 type.", _
                            value)
       End Try   
    Next                                  
    ' The example displays the following output:
    '    -79228162514264337593543950335 is outside the range of the Int32 type.
    '    Converted the Decimal value '-1034.23' to the Int32 value -1034.
    '    Converted the Decimal value '-12' to the Int32 value -12.
    '    Converted the Decimal value '0' to the Int32 value 0.
    '    Converted the Decimal value '147' to the Int32 value 147.
    '    Converted the Decimal value '199.55' to the Int32 value 200.
    '    Converted the Decimal value '9214.16' to the Int32 value 9214.
    '    79228162514264337593543950335 is outside the range of the Int32 type.
    
  • 可以调用 ParseTryParse 方法将值的字符串表示形式 Int32 转换为 Int32。 该字符串可以包含十进制或十六进制数字。 以下示例使用十进制字符串和十六进制字符串演示了分析操作。

    string string1 = "244681";
    try {
       int number1 = Int32.Parse(string1);
       Console.WriteLine(number1);
    }
    catch (OverflowException) {
       Console.WriteLine("'{0}' is out of range of a 32-bit integer.", string1);
    }
    catch (FormatException) {
       Console.WriteLine("The format of '{0}' is invalid.", string1);
    }
    
    string string2 = "F9A3C";
    try {
       int number2 = Int32.Parse(string2,
                                System.Globalization.NumberStyles.HexNumber);
       Console.WriteLine(number2);
    }
    catch (OverflowException) {
       Console.WriteLine("'{0}' is out of range of a 32-bit integer.", string2);
    }
    catch (FormatException) {
       Console.WriteLine("The format of '{0}' is invalid.", string2);
    }
    // The example displays the following output:
    //       244681
    //       1022524
    
    let string1 = "244681"
    try
        let number1 = Int32.Parse string1
        printfn $"{number1}"
    with
    | :? OverflowException ->
        printfn "'{string1}' is out of range of a 32-bit integer."
    | :? FormatException ->
        printfn $"The format of '{string1}' is invalid."
    
    let string2 = "F9A3C"
    try
        let number2 = Int32.Parse(string2, System.Globalization.NumberStyles.HexNumber)
        printfn $"{number2}"
    with 
    | :? OverflowException ->
        printfn $"'{string2}' is out of range of a 32-bit integer."
    | :? FormatException ->
        printfn $"The format of '{string2}' is invalid."
    
    // The example displays the following output:
    //       244681
    //       1022524
    
    Dim string1 As String = "244681"
    Try
       Dim number1 As Integer = Int32.Parse(string1)
       Console.WriteLine(number1)
    Catch e As OverflowException
       Console.WriteLine("'{0}' is out of range of a 32-bit integer.", string1)
    Catch e As FormatException
       Console.WriteLine("The format of '{0}' is invalid.", string1)
    End Try
    
    Dim string2 As String = "F9A3C"
    Try
       Dim number2 As Integer = Int32.Parse(string2,
                                System.Globalization.NumberStyles.HexNumber)
       Console.WriteLine(number2)
    Catch e As OverflowException
       Console.WriteLine("'{0}' is out of range of a 32-bit integer.", string2)
    Catch e As FormatException
       Console.WriteLine("The format of '{0}' is invalid.", string2)
    End Try
    ' The example displays the following output:
    '       244681
    '       1022524
    

对 Int32 值执行操作

Int32 类型支持标准数学运算,例如加法、减法、除法、乘法、求反和一元求反。 与其他整型类型一样,该 Int32 类型还支持位 ANDORXOR左移和右移运算符。

可以使用标准数值运算符比较两个 Int32 值,也可以调用 CompareToEquals 方法。

还可以调用类的成员 Math 来执行广泛的数值运算,包括获取数字的绝对值、计算整数除法的商数和余数、确定两个整数的最大值或最小值、获取数字的符号以及舍入数字。

将 Int32 表示为字符串

Int32 类型为标准和自定义数字格式字符串提供完全支持。 (有关详细信息,请参阅 格式设置类型标准数字格式字符串自定义数字格式字符串

若要将 Int32 值格式化为无前导零的整型字符串,可以调用无 ToString() 参数方法。 通过使用“D”格式说明符,还可以在字符串表示形式中包含指定数量的前导零。 通过使用“N”格式说明符,可以包括组分隔符,并指定要显示在数字的字符串表示形式的十进制数字数。 通过使用“X”格式说明符,可以将值 Int32 表示为十六进制字符串。 以下示例采用以下四种方式设置值数组 Int32 中的元素的格式。

int[] numbers = { -1403, 0, 169, 1483104 };
foreach (int number in numbers)
{
    // Display value using default formatting.
    Console.Write("{0,-8}  -->   ", number.ToString());
    // Display value with 3 digits and leading zeros.
    Console.Write("{0,11:D3}", number);
    // Display value with 1 decimal digit.
    Console.Write("{0,13:N1}", number);
    // Display value as hexadecimal.
    Console.Write("{0,12:X2}", number);
    // Display value with eight hexadecimal digits.
    Console.WriteLine("{0,14:X8}", number);
}
// The example displays the following output:
//    -1403     -->         -1403     -1,403.0    FFFFFA85      FFFFFA85
//    0         -->           000          0.0          00      00000000
//    169       -->           169        169.0          A9      000000A9
//    1483104   -->       1483104  1,483,104.0      16A160      0016A160
let numbers = [| -1403; 0; 169; 1483104 |]
for number in numbers do
    // Display value using default formatting.
    printf $"{number,-8}  -->   "
    // Display value with 3 digits and leading zeros.
    printf $"{number,11:D3}"
    // Display value with 1 decimal digit.
    printf $"{number,13:N1}"
    // Display value as hexadecimal.
    printf $"{number,12:X2}"
    // Display value with eight hexadecimal digits.
    printfn $"{number,14:X8}"


  // The example displays the following output:
  //    -1403     -->         -1403     -1,403.0    FFFFFA85      FFFFFA85
  //    0         -->           000          0.0          00      00000000
  //    169       -->           169        169.0          A9      000000A9
  //    1483104   -->       1483104  1,483,104.0      16A160      0016A160
Dim numbers() As Integer = { -1403, 0, 169, 1483104 }
For Each number As Integer In numbers
   ' Display value using default formatting.
   Console.Write("{0,-8}  -->   ", number.ToString())
   ' Display value with 3 digits and leading zeros.
   Console.Write("{0,11:D3}", number) 
   ' Display value with 1 decimal digit.
   Console.Write("{0,13:N1}", number) 
   ' Display value as hexadecimal.
   Console.Write("{0,12:X2}", number) 
   ' Display value with eight hexadecimal digits.
   Console.WriteLine("{0,14:X8}", number)
Next   
' The example displays the following output:
'    -1403     -->         -1403     -1,403.0    FFFFFA85      FFFFFA85
'    0         -->           000          0.0          00      00000000
'    169       -->           169        169.0          A9      000000A9
'    1483104   -->       1483104  1,483,104.0      16A160      0016A160

还可以通过调用ToString(Int32, Int32)方法并提供基作为方法的第二个参数,将值格式化Int32为二进制、八进制、十六进制或十六进制字符串。 以下示例调用此方法以显示整数值的数组的二进制、八进制和十六进制表示形式。

int[] numbers = { -146, 11043, 2781913 };
Console.WriteLine("{0,8}   {1,32}   {2,11}   {3,10}",
                  "Value", "Binary", "Octal", "Hex");
foreach (int number in numbers)
{
    Console.WriteLine("{0,8}   {1,32}   {2,11}   {3,10}",
                      number, Convert.ToString(number, 2),
                      Convert.ToString(number, 8),
                      Convert.ToString(number, 16));
}
// The example displays the following output:
//       Value                             Binary         Octal          Hex
//        -146   11111111111111111111111101101110   37777777556     ffffff6e
//       11043                     10101100100011         25443         2b23
//     2781913             1010100111001011011001      12471331       2a72d9
let numbers = [| -146; 11043; 2781913 |]
printfn $"""{"Value",8}   {"Binary",32}   {"Octal",11}   {"Hex",10}""" 
for number in numbers do
    printfn $"{number,8}   {Convert.ToString(number, 2),32}   {Convert.ToString(number, 8),11}   {Convert.ToString(number, 16),10}"

// The example displays the following output:
//       Value                             Binary         Octal          Hex
//        -146   11111111111111111111111101101110   37777777556     ffffff6e
//       11043                     10101100100011         25443         2b23
//     2781913             1010100111001011011001      12471331       2a72d9
Dim numbers() As Integer = { -146, 11043, 2781913 }
Console.WriteLine("{0,8}   {1,32}   {2,11}   {3,10}", _
                  "Value", "Binary", "Octal", "Hex")
For Each number As Integer In numbers
   Console.WriteLine("{0,8}   {1,32}   {2,11}   {3,10}", _
                     number, Convert.ToString(number, 2), _
                     Convert.ToString(number, 8), _
                     Convert.ToString(number, 16))
Next      
' The example displays the following output:
'       Value                             Binary         Octal          Hex
'        -146   11111111111111111111111101101110   37777777556     ffffff6e
'       11043                     10101100100011         25443         2b23
'     2781913             1010100111001011011001      12471331       2a72d9

使用非十进制 32 位整数值

除了将单个整数用作十进制值之外,你可能还希望使用整数值执行按位运算,或者使用整数值的二进制或十六进制表示形式。 Int32 值以 31 位表示,第三十二位用作符号位。 正值使用符号和数量级表示形式表示。 负值采用两个补补表示形式。 在对 Int32 值执行按位操作或处理单个位时,请务必记住这一点。 若要对任何两个非十进制值执行数值、布尔值或比较运算,这两个值都必须使用相同的表示形式。