Windows c integer types

Integral numeric types (C# reference)

The integral numeric types represent integer numbers. All integral numeric types are value types. They are also simple types and can be initialized with literals. All integral numeric types support arithmetic, bitwise logical, comparison, and equality operators.

Characteristics of the integral types

C# supports the following predefined integral types:

C# type/keyword Range Size .NET type
sbyte -128 to 127 Signed 8-bit integer System.SByte
byte 0 to 255 Unsigned 8-bit integer System.Byte
short -32,768 to 32,767 Signed 16-bit integer System.Int16
ushort 0 to 65,535 Unsigned 16-bit integer System.UInt16
int -2,147,483,648 to 2,147,483,647 Signed 32-bit integer System.Int32
uint 0 to 4,294,967,295 Unsigned 32-bit integer System.UInt32
long -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 Signed 64-bit integer System.Int64
ulong 0 to 18,446,744,073,709,551,615 Unsigned 64-bit integer System.UInt64
nint Depends on platform Signed 32-bit or 64-bit integer System.IntPtr
nuint Depends on platform Unsigned 32-bit or 64-bit integer System.UIntPtr

In all of the table rows except the last two, each C# type keyword from the leftmost column is an alias for the corresponding .NET type. The keyword and .NET type name are interchangeable. For example, the following declarations declare variables of the same type:

The nint and nuint types in the last two rows of the table are native-sized integers. They are represented internally by the indicated .NET types, but in each case the keyword and the .NET type are not interchangeable. The compiler provides operations and conversions for nint and nuint as integer types that it doesn’t provide for the pointer types System.IntPtr and System.UIntPtr . For more information, see nint and nuint types.

The default value of each integral type is zero, 0 . Each of the integral types except the native-sized types has MinValue and MaxValue constants that provide the minimum and maximum value of that type.

Use the System.Numerics.BigInteger structure to represent a signed integer with no upper or lower bounds.

Integer literals

Integer literals can be

  • decimal: without any prefix
  • hexadecimal: with the 0x or 0X prefix
  • binary: with the 0b or 0B prefix (available in C# 7.0 and later)

The following code demonstrates an example of each:

The preceding example also shows the use of _ as a digit separator, which is supported starting with C# 7.0. You can use the digit separator with all kinds of numeric literals.

The type of an integer literal is determined by its suffix as follows:

If the literal has no suffix, its type is the first of the following types in which its value can be represented: int , uint , long , ulong .

Literals are interpreted as positive values. For example, the literal 0xFF_FF_FF_FF represents the number 4294967295 of the uint type, though it has the same bit representation as the number -1 of the int type. If you need a value of a certain type, cast a literal to that type. Use the unchecked operator, if a literal value cannot be represented in the target type. For example, unchecked((int)0xFF_FF_FF_FF) produces -1 .

If the literal is suffixed by U or u , its type is the first of the following types in which its value can be represented: uint , ulong .

If the literal is suffixed by L or l , its type is the first of the following types in which its value can be represented: long , ulong .

You can use the lowercase letter l as a suffix. However, this generates a compiler warning because the letter l can be confused with the digit 1 . Use L for clarity.

If the literal is suffixed by UL , Ul , uL , ul , LU , Lu , lU , or lu , its type is ulong .

If the value represented by an integer literal exceeds UInt64.MaxValue, a compiler error CS1021 occurs.

If the determined type of an integer literal is int and the value represented by the literal is within the range of the destination type, the value can be implicitly converted to sbyte , byte , short , ushort , uint , ulong , nint or nuint :

As the preceding example shows, if the literal’s value is not within the range of the destination type, a compiler error CS0031 occurs.

You can also use a cast to convert the value represented by an integer literal to the type other than the determined type of the literal:

Conversions

You can convert any integral numeric type to any other integral numeric type. If the destination type can store all values of the source type, the conversion is implicit. Otherwise, you need to use a cast expression to perform an explicit conversion. For more information, see Built-in numeric conversions.

C# language specification

For more information, see the following sections of the C# language specification:

Тип данных Integer (Visual Basic) Integer data type (Visual Basic)

Содержит 32-разрядные (4-байтовые) целые числа со знаком в диапазоне от -2 147 483 648 до 2 147 483 647. Holds signed 32-bit (4-byte) integers that range in value from -2,147,483,648 through 2,147,483,647.

Remarks Remarks

Тип данных Integer обеспечивает оптимальную производительность на 32-разрядных процессорах. The Integer data type provides optimal performance on a 32-bit processor. Другие целочисленные типы загружаются в память и сохраняются в памяти с более низкой скоростью. The other integral types are slower to load and store from and to memory.

Значение по умолчанию для типа Integer — 0. The default value of Integer is 0.

Присваивания литералов Literal assignments

Вы можете объявить и инициализировать Integer переменную, назначив ей десятичный литерал, шестнадцатеричный литерал, Восьмеричный литерал или (начиная с Visual Basic 2017) двоичный литерал. You can declare and initialize an Integer variable by assigning it a decimal literal, a hexadecimal literal, an octal literal, or (starting with Visual Basic 2017) a binary literal. Если целочисленный литерал выходит за пределы диапазона Integer (то есть, если он меньше Int32.MinValue или больше Int32.MaxValue), возникает ошибка компиляции. If the integer literal is outside the range of Integer (that is, if it is less than Int32.MinValue or greater than Int32.MaxValue, a compilation error occurs.

В следующем примере целые числа, равные 90 946 и представленные в виде десятичного, шестнадцатеричного и двоичного литерала, назначаются значениям Integer . In the following example, integers equal to 90,946 that are represented as decimal, hexadecimal, and binary literals are assigned to Integer values.

Используйте префикс &h или &H , чтобы обозначить шестнадцатеричный литерал, префикс &b или &B обозначить двоичный литерал, а также префикс &o или &O обозначить Восьмеричный литерал. You use the prefix &h or &H to denote a hexadecimal literal, the prefix &b or &B to denote a binary literal, and the prefix &o or &O to denote an octal literal. У десятичных литералов префиксов нет. Decimal literals have no prefix.

Начиная с Visual Basic 2017, можно также использовать символ подчеркивания () в _ качестве разделителя цифр, чтобы улучшить удобочитаемость, как показано в следующем примере. Starting with Visual Basic 2017, you can also use the underscore character, _ , as a digit separator to enhance readability, as the following example shows.

Начиная с Visual Basic 15,5, можно также использовать символ подчеркивания () в _ качестве начального разделителя между префиксом и шестнадцатеричными, двоичными или восьмеричными цифрами. Starting with Visual Basic 15.5, you can also use the underscore character ( _ ) as a leading separator between the prefix and the hexadecimal, binary, or octal digits. Пример: For example:

Чтобы использовать символ подчеркивания в качестве начального разделителя, нужно добавить в файл проекта Visual Basic (*.vbproj) следующий элемент: To use the underscore character as a leading separator, you must add the following element to your Visual Basic project (*.vbproj) file:

Для получения дополнительной информации см. For more information see setting the Visual Basic language version.

Числовые литералы также могут включать I символ типа для обозначения Integer типа данных, как показано в следующем примере. Numeric literals can also include the I type character to denote the Integer data type, as the following example shows.

Советы по программированию Programming tips

Вопросы взаимодействия. Interop Considerations. При взаимоработе с компонентами, которые не записываются для платформа .NET Framework, таких как автоматизация или COM-объекты, помните, что Integer в других средах ширина данных (16 бит) отличается. If you are interfacing with components not written for the .NET Framework, such as Automation or COM objects, remember that Integer has a different data width (16 bits) in other environments. При передаче 16-разрядного аргумента такому компоненту в новом коде Visual Basic следует объявить его как Short , а не как Integer . If you are passing a 16-bit argument to such a component, declare it as Short instead of Integer in your new Visual Basic code.

Расширяющие. Widening. Тип данных Integer можно расширить до Long , Decimal , Single или Double . The Integer data type widens to Long , Decimal , Single , or Double . Это означает, что тип Integer можно преобразовать в любой из этих типов без возникновения ошибки System.OverflowException. This means you can convert Integer to any one of these types without encountering a System.OverflowException error.

Символы типа. Type Characters. При добавлении к литералу символа типа литерала I производится принудительное приведение литерала к типу данных Integer . Appending the literal type character I to a literal forces it to the Integer data type. При добавлении символа идентификатора типа % к любому идентификатору производится принудительное приведение этого идентификатора к типу Integer . Appending the identifier type character % to any identifier forces it to Integer .

Тип Framework. Framework Type. В .NET Framework данный тип соответствует структуре System.Int32. The corresponding type in the .NET Framework is the System.Int32 structure.

Диапазон Range

При попытке присвоить целочисленной переменной значение, лежащее за пределами диапазона данного типа, возникает ошибка. If you try to set a variable of an integral type to a number outside the range for that type, an error occurs. При попытке задать дробное значение оно округляется вверх или вниз до ближайшего целого значения. If you try to set it to a fraction, the number is rounded up or down to the nearest integer value. Если число находится точно посередине между двумя целыми числами, значение округляется до ближайшего четного целого. If the number is equally close to two integer values, the value is rounded to the nearest even integer. Такое поведение минимизирует ошибки округления, происходящие от постоянного округления среднего значения в одном направлении. This behavior minimizes rounding errors that result from consistently rounding a midpoint value in a single direction. В следующем коде приведены примеры округления. The following code shows examples of rounding.

Целочисленные типы (справочник по C#) Integral numeric types (C# reference)

Целочисленные типы представляют целые числа. The integral numeric types represent integer numbers. Все целочисленные типы являются типами значений. All integral numeric types are value types. Они также представляют собой простые типы и могут быть инициализированы литералами. They are also simple types and can be initialized with literals. Все целочисленные типы поддерживают арифметические операторы, побитовые логические операторы, операторы сравнения и равенства. All integral numeric types support arithmetic, bitwise logical, comparison, and equality operators.

Характеристики целочисленных типов Characteristics of the integral types

C# поддерживает следующие предварительно определенные целочисленные типы: C# supports the following predefined integral types:

Ключевое слово или тип C# C# type/keyword Диапазон Range Размер Size Тип .NET .NET type
sbyte От -128 до 127 -128 to 127 8-разрядное целое число со знаком Signed 8-bit integer System.SByte
byte От 0 до 255 0 to 255 8-разрядное целое число без знака Unsigned 8-bit integer System.Byte
short От -32 768 до 32 767 -32,768 to 32,767 16-разрядное целое число со знаком Signed 16-bit integer System.Int16
ushort От 0 до 65 535 0 to 65,535 16-разрядное целое число без знака Unsigned 16-bit integer System.UInt16
int От -2 147 483 648 до 2 147 483 647 -2,147,483,648 to 2,147,483,647 32-разрядное целое число со знаком Signed 32-bit integer System.Int32
uint От 0 до 4 294 967 295 0 to 4,294,967,295 32-разрядное целое число без знака Unsigned 32-bit integer System.UInt32
long От -9 223 372 036 854 775 808 до 9 223 372 036 854 775 807 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 64-разрядное целое число со знаком Signed 64-bit integer System.Int64
ulong От 0 до 18 446 744 073 709 551 615 0 to 18,446,744,073,709,551,615 64-разрядное целое число без знака Unsigned 64-bit integer System.UInt64
nint Зависит от платформы Depends on platform 32- или 64-разрядное целое число со знаком Signed 32-bit or 64-bit integer System.IntPtr
nuint Зависит от платформы Depends on platform 32- или 64-разрядное целое число без знака Unsigned 32-bit or 64-bit integer System.UIntPtr

Во всех строках таблицы, кроме двух последних, каждое ключевое слово типа C# из крайнего левого столбца является псевдонимом для соответствующего типа .NET. In all of the table rows except the last two, each C# type keyword from the leftmost column is an alias for the corresponding .NET type. Ключевое слово и имя типа .NET являются взаимозаменяемыми. The keyword and .NET type name are interchangeable. Например, следующие объявления объявляют переменные одного типа: For example, the following declarations declare variables of the same type:

Типы nint и nuint в последних двух строках таблицы являются целыми числами собственного размера. The nint and nuint types in the last two rows of the table are native-sized integers. В коде такие числа представлены определенными типами .NET, но в каждом случае ключевое слово и тип .NET не взаимозаменяемы. They are represented internally by the indicated .NET types, but in each case the keyword and the .NET type are not interchangeable. Для nint и nuint компилятор предоставляет преобразования и операции, как для целочисленных типов. Они отличаются от преобразований и операций для типов указателей System.IntPtr и System.UIntPtr . The compiler provides operations and conversions for nint and nuint as integer types that it doesn’t provide for the pointer types System.IntPtr and System.UIntPtr . Дополнительные сведения см. в статье о типах nint и nuint . For more information, see nint and nuint types.

Дополнительные сведения о целочисленных типах собственного размера см. в статье о nint и nuint . For information about the native-sized integer types, see nint and nuint .

По умолчанию все целочисленные типы имеют значение 0 . The default value of each integral type is zero, 0 . Все целочисленные типы, кроме целых чисел собственного размера, имеют константы MinValue и MaxValue с минимальным и максимальным значением этого типа. Each of the integral types except the native-sized types has MinValue and MaxValue constants that provide the minimum and maximum value of that type.

Используйте структуру System.Numerics.BigInteger, чтобы представить целое число со знаком без верхней и нижней границ. Use the System.Numerics.BigInteger structure to represent a signed integer with no upper or lower bounds.

Целочисленные литералы Integer literals

Целочисленные литералы могут быть: Integer literals can be

  • десятичным числом: без префикса; decimal: without any prefix
  • шестнадцатеричным числом: с префиксом 0x или 0X ; hexadecimal: with the 0x or 0X prefix
  • двоичными: с префиксом 0b или 0B (доступно в C# 7.0 и более поздних версиях). binary: with the 0b or 0B prefix (available in C# 7.0 and later)

В приведенном ниже коде показан пример каждого из них. The following code demonstrates an example of each:

В предыдущем примере также показано использование _ в качестве цифрового разделителя, который поддерживается, начиная с версии C# 7.0. The preceding example also shows the use of _ as a digit separator, which is supported starting with C# 7.0. Цифровой разделитель можно использовать со всеми видами числовых литералов. You can use the digit separator with all kinds of numeric literals.

Тип целочисленного литерала определяется его суффиксом следующим образом: The type of an integer literal is determined by its suffix as follows:

Если литерал не имеет суффикса, его типом будет первый из следующих типов, в котором может быть представлено его значение: int , uint , long , ulong . If the literal has no suffix, its type is the first of the following types in which its value can be represented: int , uint , long , ulong .

Если у литерала есть суффикс U или u , его типом будет первый из следующих типов, в котором может быть представлено его значение: uint , ulong . If the literal is suffixed by U or u , its type is the first of the following types in which its value can be represented: uint , ulong .

Если у литерала есть суффикс L или l , его типом будет первый из следующих типов, в котором может быть представлено его значение: long , ulong . If the literal is suffixed by L or l , its type is the first of the following types in which its value can be represented: long , ulong .

Строчную букву l можно использовать в качестве суффикса. You can use the lowercase letter l as a suffix. Однако при этом выдается предупреждение компилятора, так как букву l можно перепутать с цифрой 1 . However, this generates a compiler warning because the letter l can be confused with the digit 1 . Для ясности используйте L . Use L for clarity.

Если у литерала есть суффикс UL , Ul , uL , ul , LU , Lu , lU или lu , его тип — ulong . If the literal is suffixed by UL , Ul , uL , ul , LU , Lu , lU , or lu , its type is ulong .

Если значение, представленное целочисленным литералом, превышает UInt64.MaxValue, происходит ошибка компиляции CS1021. If the value represented by an integer literal exceeds UInt64.MaxValue, a compiler error CS1021 occurs.

Если определенный тип целочисленного литерала — int , а значение, представленное литералом, находится в диапазоне целевого типа, значение можно неявно преобразовать в sbyte , byte , short , ushort , uint , ulong , nint или nuint : If the determined type of an integer literal is int and the value represented by the literal is within the range of the destination type, the value can be implicitly converted to sbyte , byte , short , ushort , uint , ulong , nint or nuint :

Как показано в предыдущем примере, если значение литерала выходит за пределы диапазона целевого типа, возникает ошибка компилятора CS0031. As the preceding example shows, if the literal’s value is not within the range of the destination type, a compiler error CS0031 occurs.

Можно также использовать приведение для преобразования значения, представленного целочисленным литералом, в тип, отличный от определенного типа литерала: You can also use a cast to convert the value represented by an integer literal to the type other than the determined type of the literal:

Преобразования Conversions

Любой целочисленный тип можно преобразовать в любой другой целочисленный тип. You can convert any integral numeric type to any other integral numeric type. Если целевой тип может хранить все значения исходного типа, преобразование является неявным. If the destination type can store all values of the source type, the conversion is implicit. В противном случае необходимо использовать выражение приведения для выполнения явного преобразования. Otherwise, you need to use a cast expression to perform an explicit conversion. Для получения дополнительной информации см. статью Встроенные числовые преобразования. For more information, see Built-in numeric conversions.

Спецификация языка C# C# language specification

Дополнительные сведения см. в следующих разделах статьи Спецификация языка C#: For more information, see the following sections of the C# language specification:

Читайте также:  Alt linux hyper v
Оцените статью