Skip to content
Related Articles

Related Articles

Binary Literals and Digit Separators in C#
  • Last Updated : 30 Apr, 2019

Binary Literals

The fixed values are called as Literal. Literal is a value which is used by the variables. Before C# 7.0 six types of literals are available that are an integer, Floating-point, Character, String, Null, Boolean literals. In C# 7.0 there is one more literal is added which is known as Binary Literal. The binary literal is used to store the binary value in a variable. And the binary literal is represented by 0b. Binary literals are mainly used for bitmasks.

Example:

var num = 0b10001

Here when the compiler sees 0b in the variable value, then it automatically treated this num as a binary literal. If you try to run this on the compilers below C# 7.0, then the compiler will throw an error because this feature is introduced in C# 7.0 so, it will only work on C# 7.0 and above compilers.

Example:




// C# program to illustrate the 
// concept of binary literals.
using System;
  
class GFG {
  
    // Main method
    static public void Main()
    {
  
        // Creating binary literals 
        // by prefixing with 0b
        var num1 = 0b1001;
        var num2 = 0b01000011;
  
        Console.WriteLine("Value of Num1 is: " + num1);
        Console.WriteLine("Value of Num2 is: " + num2);
        Console.WriteLine("Char value of Num2 is: {0}",
                                 Convert.ToChar(num2));
    }
}
Output:



Value of Num1 is: 9
Value of Num2 is: 67
Char value of Num2 is: C

Digit Separator

The concept of digit separator is introduced in C# 7.0. With the help of digit separator, you can separate the large number into small parts which makes your code more readable. Underscore(_) is used as a digit separator. When you use digit separator in your code they are simply ignored by the compiler, so the compiler does not print digit separators in the output like as shown in the below example.

Example:




// C# program to illustrate the 
// concept of digit separators.
using System;
  
class GFG {
  
    // Main method
    static public void Main()
    {
  
        // Without Using digit separators
        long x = 100000022200000202;
        long z = 10000000020;
  
        Console.WriteLine("X: {0}", x);
        Console.WriteLine("Z: {0}", z);
  
        // Using digit separators
        long num1 = 1_00_10_00_00_00;
        var num2 = 0b_010_000_000_000_000_000_000_000_000;
        long num3 = 1_00_00_00_00_00_00;
        var num4 = 0b_1_1000_0000_1000_0000_0011_0000_0000_1000_0001;
  
        Console.WriteLine("Num1: {0}", num1);
        Console.WriteLine("Num2: {0}", num2);
        Console.WriteLine("Num3: {0}", num3);
        Console.WriteLine("Num4: {0}", num4);
    }
}
Output:
X: 100000022200000202
Z: 10000000020
Num1: 1000110000000000
Num2: 33554432
Num3: 1000000000000000000
Num4: 103213629569
My Personal Notes arrow_drop_up
Recommended Articles
Page :