Integer Literals

  • Integer types includes int, uint, long and ulong. Integer literals are the defined values of these types.
  • In C#, integer literals support decimal and hexadecimal forms.
  • Integer literals in octal form are not supported in C#.
  • An integer literal in decimal form is a combination of 0-9 digits. For example, 512, 1088 or 39, etc.
  • An integer literal in hexadecimal form is a combination of 0-9 digits and A-F, a-f characters with a prefix 0x or 0X.
  • The hex-digit A-F or a-f stands for 10-15 in decimal base.
  • The examples of hexadecimal form can be 0x10 (16 in decimal base), 0x2A (2x16+10=42 in decimal base) or 0XAF (10X16+15=175 in decimal base).
  • A suffix is an optional used in integer literals. It can one of U u L l UL Ul uL ul LU Lu lU lu.
  • A integer literal suffixed by U or u can only be represented as uint or ulong type. For example, ulong a = 5600u;
  • A integer literal suffixed by L or l can only be represented as long or ulong type. For example, long b = -56L;
  • A literal suffixed by UL, Ul, uL, ul, LU, Lu, lU, or lu stands for ulong typed. For example, ulong c = 0x7ALU;
Note Note
If an integer literal is out of the range of the type it stands for, a compile error will occur.

Note Note
"L" instead of "l" is recommanded to be used as a suffix of long or ulong type. Because the lower case "l" is easy to be recognized as digit "1".

Example 01-18-01:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System;

namespace TestIntLiterals
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 0x56;
            int j = 0xEF;

            //i = 0xFFFFFFFFFFFFFF;
            Console.WriteLine("i+j={0}, i+j={0:X} in hexadecimal", i + j);

            //ulong m = -0xffL;
            ulong m = 0xffL;
            ulong n = 12348UL;
            Console.WriteLine("m+n={0}, m+n={0:X} in hexadecimal", m + n);

            Console.Read();
        }
    }
}

Output

i+j=325, i+j=145 in hexadecimal
m+n=12603, m+n=313B in hexadecimal
  • Line 9-10: 2 hexadecimal form literals are assigned to 2 int variables.
  • Line 12: This line is commented out. If not, you would get a compile-time error "Cannot implicitly convert type 'long' to 'int'.". 0xFFFFFFFFFFFFFF is a long type literal and cannot be assigned to int variable implicitly.
  • Line 13: Output the addition result.0:X means outputting hexadecimal value instead of decimal value.
  • Line 15: If this line is not commented out. You will get a compile error because you cannot assign a negtive literal to ulong type.
  • Line 16-17: Define 2 ulong variables and assign literals to them.
  • Line 18: Output the addition hexadecimal result.