Int32 Estrutura

Definição

Representa um inteiro com sinal de 32 bits.

public value class int : IComparable, IComparable<int>, IConvertible, IEquatable<int>, IFormattable
public value class int : IComparable, IComparable<int>, IConvertible, IEquatable<int>, ISpanFormattable
public value class int : IComparable<int>, IConvertible, IEquatable<int>, IParsable<int>, ISpanParsable<int>, System::Numerics::IAdditionOperators<int, int, int>, System::Numerics::IAdditiveIdentity<int, int>, System::Numerics::IBinaryInteger<int>, System::Numerics::IBinaryNumber<int>, System::Numerics::IBitwiseOperators<int, int, int>, System::Numerics::IComparisonOperators<int, int>, System::Numerics::IDecrementOperators<int>, System::Numerics::IDivisionOperators<int, int, int>, System::Numerics::IEqualityOperators<int, int>, System::Numerics::IIncrementOperators<int>, System::Numerics::IMinMaxValue<int>, System::Numerics::IModulusOperators<int, int, int>, System::Numerics::IMultiplicativeIdentity<int, int>, System::Numerics::IMultiplyOperators<int, int, int>, System::Numerics::INumber<int>, System::Numerics::INumberBase<int>, System::Numerics::IShiftOperators<int, int>, System::Numerics::ISignedNumber<int>, System::Numerics::ISubtractionOperators<int, int, int>, System::Numerics::IUnaryNegationOperators<int, int>, System::Numerics::IUnaryPlusOperators<int, int>
public value class int : IComparable, IConvertible, IFormattable
public value class int : IComparable, IComparable<int>, IEquatable<int>, IFormattable
public struct Int32 : IComparable, IComparable<int>, IConvertible, IEquatable<int>, IFormattable
public readonly struct Int32 : IComparable, IComparable<int>, IConvertible, IEquatable<int>, IFormattable
public readonly struct Int32 : IComparable, IComparable<int>, IConvertible, IEquatable<int>, ISpanFormattable
public readonly struct Int32 : IComparable<int>, IConvertible, IEquatable<int>, IParsable<int>, ISpanParsable<int>, System.Numerics.IAdditionOperators<int,int,int>, System.Numerics.IAdditiveIdentity<int,int>, System.Numerics.IBinaryInteger<int>, System.Numerics.IBinaryNumber<int>, System.Numerics.IBitwiseOperators<int,int,int>, System.Numerics.IComparisonOperators<int,int>, System.Numerics.IDecrementOperators<int>, System.Numerics.IDivisionOperators<int,int,int>, System.Numerics.IEqualityOperators<int,int>, System.Numerics.IIncrementOperators<int>, System.Numerics.IMinMaxValue<int>, System.Numerics.IModulusOperators<int,int,int>, System.Numerics.IMultiplicativeIdentity<int,int>, System.Numerics.IMultiplyOperators<int,int,int>, System.Numerics.INumber<int>, System.Numerics.INumberBase<int>, System.Numerics.IShiftOperators<int,int>, System.Numerics.ISignedNumber<int>, System.Numerics.ISubtractionOperators<int,int,int>, System.Numerics.IUnaryNegationOperators<int,int>, System.Numerics.IUnaryPlusOperators<int,int>
[System.Serializable]
public struct Int32 : IComparable, IConvertible, IFormattable
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public struct Int32 : IComparable, IComparable<int>, IConvertible, IEquatable<int>, IFormattable
public struct Int32 : IComparable, IComparable<int>, IEquatable<int>, IFormattable
type int = struct
    interface IConvertible
    interface IFormattable
type int = struct
    interface IConvertible
    interface ISpanFormattable
    interface IFormattable
type int = struct
    interface IConvertible
    interface IFormattable
    interface IParsable<int>
    interface ISpanFormattable
    interface ISpanParsable<int>
    interface IAdditionOperators<int, int, int>
    interface IAdditiveIdentity<int, int>
    interface IBinaryInteger<int>
    interface IBinaryNumber<int>
    interface IBitwiseOperators<int, int, int>
    interface IComparisonOperators<int, int>
    interface IEqualityOperators<int, int>
    interface IDecrementOperators<int>
    interface IDivisionOperators<int, int, int>
    interface IIncrementOperators<int>
    interface IModulusOperators<int, int, int>
    interface IMultiplicativeIdentity<int, int>
    interface IMultiplyOperators<int, int, int>
    interface INumber<int>
    interface INumberBase<int>
    interface ISubtractionOperators<int, int, int>
    interface IUnaryNegationOperators<int, int>
    interface IUnaryPlusOperators<int, int>
    interface IShiftOperators<int, int>
    interface IMinMaxValue<int>
    interface ISignedNumber<int>
[<System.Serializable>]
type int = struct
    interface IFormattable
    interface IConvertible
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type int = struct
    interface IFormattable
    interface IConvertible
type int = struct
    interface IFormattable
Public Structure Int32
Implements IComparable, IComparable(Of Integer), IConvertible, IEquatable(Of Integer), IFormattable
Public Structure Int32
Implements IComparable, IComparable(Of Integer), IConvertible, IEquatable(Of Integer), ISpanFormattable
Public Structure Int32
Implements IAdditionOperators(Of Integer, Integer, Integer), IAdditiveIdentity(Of Integer, Integer), IBinaryInteger(Of Integer), IBinaryNumber(Of Integer), IBitwiseOperators(Of Integer, Integer, Integer), IComparable(Of Integer), IComparisonOperators(Of Integer, Integer), IConvertible, IDecrementOperators(Of Integer), IDivisionOperators(Of Integer, Integer, Integer), IEqualityOperators(Of Integer, Integer), IEquatable(Of Integer), IIncrementOperators(Of Integer), IMinMaxValue(Of Integer), IModulusOperators(Of Integer, Integer, Integer), IMultiplicativeIdentity(Of Integer, Integer), IMultiplyOperators(Of Integer, Integer, Integer), INumber(Of Integer), INumberBase(Of Integer), IParsable(Of Integer), IShiftOperators(Of Integer, Integer), ISignedNumber(Of Integer), ISpanParsable(Of Integer), ISubtractionOperators(Of Integer, Integer, Integer), IUnaryNegationOperators(Of Integer, Integer), IUnaryPlusOperators(Of Integer, Integer)
Public Structure Int32
Implements IComparable, IConvertible, IFormattable
Public Structure Int32
Implements IComparable, IComparable(Of Integer), IEquatable(Of Integer), IFormattable
Herança
Atributos
Implementações
IComparable IComparable<Int32> IConvertible IEquatable<Int32> IFormattable ISpanFormattable IComparable<TOther> IComparable<TSelf> IEquatable<TOther> IEquatable<TSelf> IParsable<Int32> IParsable<TSelf> ISpanParsable<Int32> ISpanParsable<TSelf> IAdditionOperators<Int32,Int32,Int32> IAdditionOperators<TSelf,TSelf,TSelf> IAdditiveIdentity<Int32,Int32> IAdditiveIdentity<TSelf,TSelf> IBinaryInteger<Int32> IBinaryNumber<Int32> IBinaryNumber<TSelf> IBitwiseOperators<Int32,Int32,Int32> IBitwiseOperators<TSelf,TSelf,TSelf> System.Numerics.IComparisonOperators<Int32,Int32> System.Numerics.IComparisonOperators<TSelf,TSelf> IDecrementOperators<Int32> IDecrementOperators<TSelf> IDivisionOperators<Int32,Int32,Int32> IDivisionOperators<TSelf,TSelf,TSelf> System.Numerics.IEqualityOperators<Int32,Int32> System.Numerics.IEqualityOperators<TSelf,TOther> System.Numerics.IEqualityOperators<TSelf,TSelf> IIncrementOperators<Int32> IIncrementOperators<TSelf> IMinMaxValue<Int32> IModulusOperators<Int32,Int32,Int32> IModulusOperators<TSelf,TSelf,TSelf> IMultiplicativeIdentity<Int32,Int32> IMultiplicativeIdentity<TSelf,TSelf> IMultiplyOperators<Int32,Int32,Int32> IMultiplyOperators<TSelf,TSelf,TSelf> INumber<Int32> INumber<TSelf> INumberBase<Int32> INumberBase<TSelf> System.Numerics.IShiftOperators<Int32,Int32> System.Numerics.IShiftOperators<TSelf,TSelf> ISignedNumber<Int32> ISubtractionOperators<Int32,Int32,Int32> ISubtractionOperators<TSelf,TSelf,TSelf> IUnaryNegationOperators<Int32,Int32> IUnaryNegationOperators<TSelf,TSelf> IUnaryPlusOperators<Int32,Int32> IUnaryPlusOperators<TSelf,TSelf>

Comentários

Int32 é um tipo de valor imutável que representa inteiros com sinal com valores que variam de 2.147.483.648 negativos (que é representado pela Int32.MinValue constante) a 2.147.483.647 positivos (que é representado pela Int32.MaxValue constante). O .NET também inclui um tipo de valor inteiro de 32 bits sem sinal, UInt32que representa valores que variam de 0 a 4.294.967.295.

Criando uma instância de um valor Int32

Você pode criar uma instância de um Int32 valor de várias maneiras:

  • Você pode declarar uma Int32 variável e atribuir a ela um valor inteiro literal que está dentro do intervalo do Int32 tipo de dados. O exemplo a seguir declara duas Int32 variáveis e atribui-lhes valores dessa forma.

    int number1 = 64301;
    int number2 = 25548612;
    
    let number1 = 64301
    let number2 = 25548612
    
    Dim number1 As Integer = 64301
    Dim number2 As Integer = 25548612
    
  • Você pode atribuir o valor de um tipo inteiro cujo intervalo é um subconjunto do Int32 tipo. Essa é uma conversão de expansão que não requer um operador de conversão 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 value2
    
    Dim value1 As SByte = 124
    Dim value2 As Int16 = 1618
    
    Dim number1 As Integer = value1
    Dim number2 As Integer = value2
    
  • Você pode atribuir o valor de um tipo numérico cujo intervalo excede o Int32 do tipo. Essa é uma conversão de estreitamento, portanto, requer um operador de conversão em C# ou F#e um método de conversão no Visual Basic, se Option Strict estiver ativado. Se o valor numérico for um Single, Doubleou Decimal valor que inclua um componente fracionário, o tratamento de sua parte fracionária dependerá do compilador executar a conversão. O exemplo a seguir executa conversões de restrição 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("{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
    
  • Você pode chamar um método da Convert classe para converter qualquer tipo com suporte em um Int32 valor. Isso é possível porque Int32 dá suporte à IConvertible interface. O exemplo a seguir ilustra a conversão de uma matriz de Decimal valores em Int32 valores.

    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.
    
  • Você pode chamar o método ou o Parse método para converter a representação de cadeia de caracteres de um Int32 valor em um Int32.TryParse A cadeia de caracteres pode conter dígitos decimal ou hexadecimal. O exemplo a seguir ilustra a operação de análise usando uma cadeia de caracteres decimal e hexadecimal.

    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
    

Realizando operações em valores Int32

O Int32 tipo dá suporte a operações matemáticas padrão, como adição, subtração, divisão, multiplicação, negação e negação unária. Assim como os outros tipos integrais, o Int32 tipo também dá suporte aos operadores bit a bit AND, OR, XORde deslocamento para a esquerda e de deslocamento para a direita.

Você pode usar os operadores numéricos padrão para comparar dois Int32 valores ou pode chamar o método ou Equals o CompareTo método.

Também é possível chamar os membros da classe Math para realizar uma ampla variedade de operações numéricas, inclusive obter o valor absoluto de um número, calcular o quociente e o restante da divisão integral, determinando o valor máximo ou mínimo de dois inteiros, obter o sinal de um número e arredondar um número.

Representando um Int32 como uma cadeia de caracteres

O Int32 tipo 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ão e Cadeias de Caracteres de Formato Numérico Personalizado.)

Para formatar um Int32 valor como uma cadeia de caracteres integral sem zeros à esquerda, você pode chamar o método sem ToString() parâmetros. Usando o especificador de formato "D", você também pode incluir um número especificado de zeros à esquerda na representação de 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 Int32 valor como uma cadeia de caracteres hexadecimal. O exemplo a seguir formata os elementos em uma matriz de Int32 valores destas quatro maneiras.

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 Int32 valor como uma cadeia de caracteres binária, octal, decimal ou hexadecimal chamando o ToString(Int32, Int32) método 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 hexadecimal 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

Trabalhando com valores inteiros de 32 bits não decimais

Além de trabalhar com inteiros individuais como valores decimais, convém executar operações bit a bit com valores inteiros ou trabalhar com as representações binárias ou hexadecimal de valores inteiros. Int32 os valores são representados em 31 bits, com o bit de trinta segundos usado como um bit de sinal. Os valores positivos são representados usando a representação de sinal e magnitude. Os valores negativos estão na representação complementar de dois. Isso é importante ter em mente quando você executa operações bit a bit em Int32 valores ou quando trabalha com bits individuais. Para executar uma operação numérica, booliana ou de comparação em dois valores não decimais, ambos os valores devem usar a mesma representação.

Campos

MaxValue

Representa o maior valor possível de um Int32. Este campo é constante.

MinValue

Representa o menor valor possível de Int32. Este campo é constante.

Métodos

Abs(Int32)

Calcula o absoluto de um valor.

Clamp(Int32, Int32, Int32)

Fixa um valor a um valor mínimo e máximo inclusivo.

CompareTo(Int32)

Compara essa instância com um inteiro com sinal de 32 bits especificado e retorna uma indicação dos valores relativos.

CompareTo(Object)

Compara essa instância com um objeto especificado e retorna uma indicação dos valores relativos.

CopySign(Int32, Int32)

Copia o sinal de um valor para o sinal de outro valor.

CreateChecked<TOther>(TOther)

Cria uma instância do tipo atual a partir de um valor, gerando uma exceção de estouro para quaisquer valores que fiquem fora do intervalo representável do tipo atual.

CreateSaturating<TOther>(TOther)

Cria uma instância do tipo atual a partir de um valor, saturando todos os valores que estão fora do intervalo representável do tipo atual.

CreateTruncating<TOther>(TOther)

Cria uma instância do tipo atual a partir de um valor, truncando quaisquer valores que fiquem fora do intervalo representável do tipo atual.

DivRem(Int32, Int32)

Calcula o quociente e o restante de dois valores.

Equals(Int32)

Retorna um valor que indica se a instância é igual a um valor Int32 especificado.

Equals(Object)

Retorna um valor que indica se a instância é igual a um objeto especificado.

GetHashCode()

Retorna o código hash para a instância.

GetTypeCode()

Retorna o TypeCode para tipo de valor Int32.

IsEvenInteger(Int32)

Determina se um valor representa um número integral uniforme.

IsNegative(Int32)

Determina se um valor é negativo.

IsOddInteger(Int32)

Determina se um valor representa um número integral ímpar.

IsPositive(Int32)

Determina se um valor é positivo.

IsPow2(Int32)

Determina se um valor é uma potência de dois.

LeadingZeroCount(Int32)

Calcula o número de zeros à esquerda em um valor.

Log2(Int32)

Calcula o log2 de um valor.

Max(Int32, Int32)

Compara dois valores com a computação que é maior.

MaxMagnitude(Int32, Int32)

Compara dois valores com a computação que é maior.

Min(Int32, Int32)

Compara dois valores com a computação menor.

MinMagnitude(Int32, Int32)

Compara dois valores com a computação menor.

Parse(ReadOnlySpan<Char>, IFormatProvider)

Analisa um intervalo de caracteres em um valor.

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Converte a representação de intervalo de um número em um formato específico da cultura e um estilo especificados em seu equivalente de inteiro com sinal de 32 bits.

Parse(String)

Converte a representação de cadeia de caracteres de um número no inteiro com sinal de 32 bits equivalente.

Parse(String, IFormatProvider)

Converte a representação de cadeia de caracteres de um número em um formato específico da cultura especificado em seu equivalente de inteiro com sinal de 32 bits.

Parse(String, NumberStyles)

Converte a representação de cadeia de caracteres de um número em um estilo especificado em um inteiro com sinal de 32 bits equivalente.

Parse(String, NumberStyles, IFormatProvider)

Converte a representação de cadeia de caracteres de um número em um estilo e formato específico da cultura especificados em seu equivalente de inteiro com sinal de 32 bits.

PopCount(Int32)

Calcula o número de bits definidos em um valor.

RotateLeft(Int32, Int32)

Gira um valor deixado por um determinado valor.

RotateRight(Int32, Int32)

Gira um valor direito em um determinado valor.

Sign(Int32)

Calcula o sinal de um valor.

ToString()

Converte o valor numérico dessa instância na representação da cadeia de caracteres equivalente.

ToString(IFormatProvider)

Converte o valor numérico dessa instância na representação da cadeia de caracteres equivalente usando as informações de formato específicas da cultura.

ToString(String)

Converte o valor numérico dessa instância na representação da cadeia de caracteres equivalente usando o formato especificado.

ToString(String, IFormatProvider)

Converte o valor numérico dessa instância na representação da cadeia de caracteres equivalente usando o formato especificado e as informações de formato específicas da cultura especificada.

TrailingZeroCount(Int32)

Calcula o número de zeros à direita em um valor.

TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider)

Tenta formatar o valor da instância de número inteiro atual para o intervalo de caracteres fornecido.

TryParse(ReadOnlySpan<Char>, IFormatProvider, Int32)

Tenta analisar um intervalo de caracteres em um valor.

TryParse(ReadOnlySpan<Char>, Int32)

Converte a representação de intervalo de um número em um formato específico da cultura e um estilo especificados em seu equivalente de inteiro com sinal de 32 bits. Um valor retornado indica se a conversão foi bem-sucedida.

TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Int32)

Converte a representação de intervalo de um número em um formato específico da cultura e um estilo especificados em seu equivalente de inteiro com sinal de 32 bits. Um valor retornado indica se a conversão foi bem-sucedida.

TryParse(String, IFormatProvider, Int32)
TryParse(String, Int32)

Converte a representação de cadeia de caracteres de um número no inteiro com sinal de 32 bits equivalente. Um valor retornado indica se a conversão foi bem-sucedida.

TryParse(String, NumberStyles, IFormatProvider, Int32)

Converte a representação de cadeia de caracteres de um número em um estilo e formato específico da cultura especificados em seu equivalente de inteiro com sinal de 32 bits. Um valor retornado indica se a conversão foi bem-sucedida.

Implantações explícitas de interface

IBinaryInteger<Int32>.GetByteCount()

Obtém o número de bytes que serão gravados como parte de TryWriteLittleEndian(Span<Byte>, Int32).

IBinaryInteger<Int32>.GetShortestBitLength()

Obtém o comprimento, em bits, da representação complementar dos dois mais curtos do valor atual.

IBinaryInteger<Int32>.TryWriteBigEndian(Span<Byte>, Int32)

Tenta gravar o valor atual, no formato big-endian, em um determinado intervalo.

IBinaryInteger<Int32>.TryWriteLittleEndian(Span<Byte>, Int32)

Tenta gravar o valor atual, no formato little-endian, em um determinado intervalo.

IComparable.CompareTo(Object)

Compara essa instância com um objeto especificado e retorna uma indicação dos valores relativos.

IConvertible.GetTypeCode()

Retorna o TypeCode para tipo de valor Int32.

IConvertible.ToBoolean(IFormatProvider)

Para obter uma descrição desse membro, confira ToBoolean(IFormatProvider).

IConvertible.ToByte(IFormatProvider)

Para obter uma descrição desse membro, confira ToByte(IFormatProvider).

IConvertible.ToChar(IFormatProvider)

Para obter uma descrição desse membro, confira ToChar(IFormatProvider).

IConvertible.ToDateTime(IFormatProvider)

Não há suporte para esta conversão. A tentativa de usar esse método lança um InvalidCastException.

IConvertible.ToDecimal(IFormatProvider)

Para obter uma descrição desse membro, confira ToDecimal(IFormatProvider).

IConvertible.ToDouble(IFormatProvider)

Para obter uma descrição desse membro, confira ToDouble(IFormatProvider).

IConvertible.ToInt16(IFormatProvider)

Para obter uma descrição desse membro, confira ToInt16(IFormatProvider).

IConvertible.ToInt32(IFormatProvider)

Para obter uma descrição desse membro, confira ToInt32(IFormatProvider).

IConvertible.ToInt64(IFormatProvider)

Para obter uma descrição desse membro, confira ToInt64(IFormatProvider).

IConvertible.ToSByte(IFormatProvider)

Para obter uma descrição desse membro, confira ToSByte(IFormatProvider).

IConvertible.ToSingle(IFormatProvider)

Para obter uma descrição desse membro, confira ToSingle(IFormatProvider).

IConvertible.ToType(Type, IFormatProvider)

Para obter uma descrição desse membro, confira ToType(Type, IFormatProvider).

IConvertible.ToUInt16(IFormatProvider)

Para obter uma descrição desse membro, confira ToUInt16(IFormatProvider).

IConvertible.ToUInt32(IFormatProvider)

Para obter uma descrição desse membro, confira ToUInt32(IFormatProvider).

IConvertible.ToUInt64(IFormatProvider)

Para obter uma descrição desse membro, confira ToUInt64(IFormatProvider).

Aplica-se a

Acesso thread-safe

Todos os membros desse tipo são thread-safe. Os membros que aparentam modificar efetivamente o estado retornam uma nova instância inicializada com o novo valor. Assim como acontece com qualquer outro tipo, a leitura e a gravação em uma variável compartilhada que contém uma instância desse tipo devem ser protegidas por um bloqueio para garantir thread-safe.

Confira também