Tipos numéricos enteros (referencia de C#)Integral numeric types (C# reference)
Los tipos numéricos integrales representan números enteros.The integral numeric types represent integer numbers. Todos los tipos numéricos integrales son tipos de valor.All integral numeric types are value types. También son tipos simples y se pueden inicializar con literales.They are also simple types and can be initialized with literals. Todos los tipos numéricos enteros admiten operadores aritméticos, lógicos bit a bit, de comparación y de igualdad.All integral numeric types support arithmetic, bitwise logical, comparison, and equality operators.
Características de los tipos enterosCharacteristics of the integral types
C# admite los siguientes tipos enteros predefinidos:C# supports the following predefined integral types:
Palabra clave/tipo de C#C# type/keyword | IntervaloRange | TamañoSize | Tipo de .NET.NET type |
---|---|---|---|
sbyte |
De -128 a 127-128 to 127 | Entero de 8 bits con signoSigned 8-bit integer | System.SByte |
byte |
De 0 a 2550 to 255 | Entero de 8 bits sin signoUnsigned 8-bit integer | System.Byte |
short |
De -32 768 a 32 767-32,768 to 32,767 | Entero de 16 bits con signoSigned 16-bit integer | System.Int16 |
ushort |
De 0 a 65.5350 to 65,535 | Entero de 16 bits sin signoUnsigned 16-bit integer | System.UInt16 |
int |
De -2.147.483.648 a 2.147.483.647-2,147,483,648 to 2,147,483,647 | Entero de 32 bits con signoSigned 32-bit integer | System.Int32 |
uint |
De 0 a 4.294.967.2950 to 4,294,967,295 | Entero de 32 bits sin signoUnsigned 32-bit integer | System.UInt32 |
long |
De -9.223.372.036.854.775.808 a 9.223.372.036.854.775.807-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | Entero de 64 bits con signoSigned 64-bit integer | System.Int64 |
ulong |
De 0 a 18.446.744.073.709.551.6150 to 18,446,744,073,709,551,615 | Entero de 64 bits sin signoUnsigned 64-bit integer | System.UInt64 |
En la tabla anterior, cada palabra clave de tipo de C# de la columna ubicada más a la izquierda es un alias del tipo de .NET correspondiente.In the preceding table, each C# type keyword from the leftmost column is an alias for the corresponding .NET type. Son intercambiables.They are interchangeable. Por ejemplo, en las declaraciones siguientes se declaran variables del mismo tipo:For example, the following declarations declare variables of the same type:
int a = 123;
System.Int32 b = 123;
El valor predeterminado de cada tipo entero es cero, 0
.The default value of each integral type is zero, 0
. Cada uno de los tipos enteros tiene las constantes MinValue
y MaxValue
que proporcionan el valor mínimo y máximo de ese tipo.Each of the integral types has the MinValue
and MaxValue
constants that provide the minimum and maximum value of that type.
Use la estructura System.Numerics.BigInteger para representar un entero con signo sin límite superior ni inferior.Use the System.Numerics.BigInteger structure to represent a signed integer with no upper or lower bounds.
Literales enterosInteger literals
Los literales enteros pueden serInteger literals can be
- decimales: sin ningún prefijodecimal: without any prefix
- hexadecimales: con el prefijo de
0x
o0X
hexadecimal: with the0x
or0X
prefix - binarios: con el prefijo
0b
o0B
(disponible en C# 7.0 y versiones posteriores)binary: with the0b
or0B
prefix (available in C# 7.0 and later)
En el código siguiente se muestra un ejemplo de cada uno de ellos:The following code demonstrates an example of each:
var decimalLiteral = 42;
var hexLiteral = 0x2A;
var binaryLiteral = 0b_0010_1010;
En el ejemplo anterior también se muestra el uso de _
como un separador de dígitos, que se admite a partir de C# 7.0.The preceding example also shows the use of _
as a digit separator, which is supported starting with C# 7.0. Puede usar el separador de dígitos con todos los tipos de literales numéricos.You can use the digit separator with all kinds of numeric literals.
El tipo de un literal entero viene determinado por su sufijo, como se indica a continuación:The type of an integer literal is determined by its suffix as follows:
Si el literal no tiene sufijo, su tipo es el primero de los siguientes tipos en el que se puede representar su valor:
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
.Si un literal entero tiene el sufijo
U
ou
, su tipo es el primero de los siguientes tipos en el que se puede representar su valor:uint
,ulong
.If the literal is suffixed byU
oru
, its type is the first of the following types in which its value can be represented:uint
,ulong
.Si un literal entero tiene el sufijo
L
ol
, su tipo es el primero de los siguientes tipos en el que se puede representar su valor:long
,ulong
.If the literal is suffixed byL
orl
, its type is the first of the following types in which its value can be represented:long
,ulong
.Nota
Puede usar la letra minúscula
l
como sufijo.You can use the lowercase letterl
as a suffix. Sin embargo, esto genera una advertencia del compilador porque la letral
se confunde fácilmente con el dígito1
.However, this generates a compiler warning because the letterl
can be confused with the digit1
. UseL
para mayor claridad.UseL
for clarity.Si el literal tiene como sufijo
UL
,Ul
,uL
,ul
,LU
,Lu
,lU
olu
, su tipo esulong
.If the literal is suffixed byUL
,Ul
,uL
,ul
,LU
,Lu
,lU
, orlu
, its type isulong
.
Si el valor que representa un literal entero supera UInt64.MaxValue, se produce un error de compilación CS1021.If the value represented by an integer literal exceeds UInt64.MaxValue, a compiler error CS1021 occurs.
Si el tipo determinado de un literal entero es int
y el valor que representa el literal está dentro del rango del tipo de destino, el valor se puede convertir de forma implícita en sbyte
, byte
, short
, ushort
, uint
o ulong
: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
, or ulong
:
byte a = 17;
byte b = 300; // CS0031: Constant value '300' cannot be converted to a 'byte'
Como se muestra en el ejemplo anterior, si el valor del literal no está dentro del intervalo del tipo de destino, se produce el error CS0031 del compilador.As the preceding example shows, if the literal's value is not within the range of the destination type, a compiler error CS0031 occurs.
También puede usar una conversión para convertir el valor representado por un literal entero en un tipo que no sea el determinado del literal: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:
var signedByte = (sbyte)42;
var longVariable = (long)42;
ConversionesConversions
Puede convertir un tipo numérico entero en cualquier otro tipo numérico entero.You can convert any integral numeric type to any other integral numeric type. Si el tipo de destino puede almacenar todos los valores del tipo de origen, la conversión es implícita.If the destination type can store all values of the source type, the conversion is implicit. De lo contrario, debe usar una expresión Cast para realizar una conversión explícita.Otherwise, you need to use a cast expression to perform an explicit conversion. Para obtener más información, consulte Conversiones numéricas integradas.For more information, see Built-in numeric conversions.
Especificación del lenguaje C#C# language specification
Para más información, vea las secciones siguientes de la Especificación del lenguaje C#:For more information, see the following sections of the C# language specification: