Nota
O acesso a esta página requer autorização. Pode tentar iniciar sessão ou alterar os diretórios.
O acesso a esta página requer autorização. Pode tentar alterar os diretórios.
Observação
Este artigo fornece observações complementares à documentação de referência para esta API.
Int32 é um tipo de valor imutável que representa inteiros assinados com valores que variam de 2.147.483.648 negativos (que são representados pela constante Int32.MinValue) até 2.147.483.647 positivos (que são representados pela constante Int32.MaxValue). O .NET também inclui um tipo de valor inteiro de 32 bits não assinado, UInt32, que representa valores que variam de 0 a 4.294.967.295.
Instanciar um valor Int32
Você pode instanciar um valor de Int32 de várias maneiras:
Você pode declarar uma variável Int32 e atribuir-lhe um valor inteiro literal que esteja dentro do intervalo do tipo de dados Int32. O exemplo a seguir declara duas variáveis Int32 e atribui-lhes valores dessa maneira.
int number1 = 64301; int number2 = 25548612;let number1 = 64301 let number2 = 25548612Dim number1 As Integer = 64301 Dim number2 As Integer = 25548612Você pode atribuir o valor de um tipo inteiro cujo intervalo é um subconjunto do tipo Int32. Esta é uma conversão de ampliação que não requer um operador cast em C# ou um método de conversão no Visual Basic, mas requer um em 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 value2Dim value1 As SByte = 124 Dim value2 As Int16 = 1618 Dim number1 As Integer = value1 Dim number2 As Integer = value2Você pode atribuir o valor de um tipo numérico cujo intervalo excede o do tipo Int32. Essa é uma conversão de estreitamento, portanto, requer um operador cast em C# ou F# e um método de conversão no Visual Basic se
Option Strictestiver ativado. Se o valor numérico for um valor Single, Doubleou Decimal que inclua um componente fracionário, a manipulação de sua parte fracionária dependerá do compilador que executa a conversão. O exemplo a seguir executa conversões de estreitamento para atribuir vários valores numéricos a Int32 variáveis.long lNumber = 163245617; try { int number1 = (int) lNumber; Console.WriteLine(number1); } catch (OverflowException) { Console.WriteLine($"{lNumber} is out of range of an Int32."); } double dbl2 = 35901.997; try { int number2 = (int) dbl2; Console.WriteLine(number2); } catch (OverflowException) { Console.WriteLine($"{dbl2} is out of range of an Int32."); } BigInteger bigNumber = 132451; try { int number3 = (int) bigNumber; Console.WriteLine(number3); } catch (OverflowException) { Console.WriteLine($"{bigNumber} is out of range of an Int32."); } // The example displays the following output: // 163245617 // 35902 // 132451let 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 // 132451Dim 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 ' 132451Você pode chamar um método da classe Convert para converter qualquer tipo suportado em um valor Int32. Isso é possível porque Int32 suporta a interface IConvertible. O exemplo a seguir ilustra a conversão de uma matriz de valores de Decimal em valores Int32.
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 {value.GetType().Name} value '{value}' to the {result.GetType().Name} value {result}."); } catch (OverflowException) { Console.WriteLine($"{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.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.Você pode chamar o método Parse ou TryParse para converter a representação de cadeia de caracteres de um valor Int32 em um Int32. A cadeia de caracteres pode conter dígitos decimais ou hexadecimais. O exemplo a seguir ilustra a operação de análise usando uma cadeia decimal e uma cadeia hexadecimal.
string string1 = "244681"; try { int number1 = Int32.Parse(string1); Console.WriteLine(number1); } catch (OverflowException) { Console.WriteLine($"'{string1}' is out of range of a 32-bit integer."); } catch (FormatException) { Console.WriteLine($"The format of '{string1}' is invalid."); } string string2 = "F9A3C"; try { int number2 = Int32.Parse(string2, System.Globalization.NumberStyles.HexNumber); Console.WriteLine(number2); } catch (OverflowException) { Console.WriteLine($"'{string2}' is out of range of a 32-bit integer."); } catch (FormatException) { Console.WriteLine($"The format of '{string2}' is invalid."); } // The example displays the following output: // 244681 // 1022524let 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 // 1022524Dim 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
Executar operações em valores Int32
O tipo Int32 suporta operações matemáticas padrão, como adição, subtração, divisão, multiplicação, negação e negação unária. Como os outros tipos integrais, o tipo Int32 também suporta os operadores bitwise AND, OR, XOR, deslocamento à esquerda e deslocamento à direita.
Você pode usar os operadores numéricos padrão para comparar dois valores Int32 ou pode chamar o método CompareTo ou Equals.
Você também pode chamar os membros da classe Math para executar uma ampla gama de operações numéricas, incluindo obter o valor absoluto de um número, calcular o quociente e o restante da divisão integral, determinar o valor máximo ou mínimo de dois inteiros, obter o sinal de um número e arredondar um número.
Representar um Int32 como uma cadeia de caracteres
O tipo Int32 fornece suporte total para cadeias de caracteres de formato numérico padrão e personalizado. (Para obter mais informações, consulte Tipos de formatação, Cadeias de caracteres de formato numérico padrãoe Cadeias de caracteres de formato numérico personalizado.)
Para formatar um valor Int32 como uma cadeia de caracteres integral sem zeros à esquerda, você pode chamar o método ToString() sem parâmetros. Usando o especificador de formato "D", você também pode incluir um número especificado de zeros à esquerda na representação da cadeia de caracteres. Usando o especificador de formato "N", você pode incluir separadores de grupo e especificar o número de dígitos decimais a serem exibidos na representação de cadeia de caracteres do número. Usando o especificador de formato "X", você pode representar um valor Int32 como uma cadeia de caracteres hexadecimal. O exemplo a seguir formata os elementos em um array de valores de Int32 de quatro maneiras diferentes.
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
Você também pode formatar um valor Int32 como uma cadeia de caracteres binária, octal, decimal ou hexadecimal chamando o método ToString(Int32, Int32) e fornecendo a base como o segundo parâmetro do método. O exemplo a seguir chama esse método para exibir as representações binárias, octais e hexadecimais de uma matriz de valores inteiros.
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
Trabalhar com valores inteiros de 32 bits não decimais
Além de trabalhar com inteiros individuais como valores decimais, você pode querer executar operações bit a bit com valores inteiros ou trabalhar com representações binárias ou hexadecimais de valores inteiros. Int32 valores são representados em 31 bits, com o trigésimo segundo bit usado como um bit de sinal. Os valores positivos são representados usando representação de sinal e magnitude. Os valores negativos estão na representação do complemento de dois. Isso é importante ter em mente quando você executa operações bit a bit em valores Int32 ou quando trabalha com bits individuais. Para executar uma operação numérica, booleana ou de comparação em quaisquer dois valores não decimais, ambos os valores devem usar a mesma representação.