Introduction
C# is a simple, high-level, general-purpose language. It supports the Object-oriented programming paradigm. Microsoft developed it under the .NET platform. It is much similar to C/C++. C# can be used for web development, web services, and desktop application development.
Recommended Topic, Palindrome in C# and Ienumerable vs Iqueryable.
Binary Literals
Literals are the constant values assigned to variables or can be used directly in C#. There are various types of literal defining the different sets of constant values. In the earlier versions of C# below C# 7.0, there were 6 types available in C#. Integer, floating-point, boolean, character, string, and NULL are the six literals present in C# below 7.0. From C# 7.0 and above, one more literal was added, called binary literal. Binary literal are the constant values in binary format, 0 or 1.
Before this, only decimal and hexadecimal values could be stored in C#, but with the addition of binary literals, it became possible for us to store the binary values. To specify a value to be binary, we have to give it 0b as a prefix. Below is an example of how you can store the binary value of 10 in a variable.
var temp = 0b1010;
Here, you can see that we have used the 0b prefix to specify that the literal is binary and has to be stored as a binary literal in variable temp.
Note: If the same statement is written in earlier versions of C# that is below 7.0, then it will raise an error as it is introduced after C# 7.0.
We can use different built-in functions to typecast the binary literals to other data types. For example, we can use ToChar or ToInt32 to convert the binary literals to character or integer data types. By default, the integer value is printed when we output/print the binary literal.
C# implementation to demonstrate Binary Literals
/* Program to demonstrate the use of binary literals in C# */
using System;
class Ninjas{
/* Driver Function */
static public void Main()
{
/* Specifying binary literals with 0b and storing the values in variables a and b */
var a = 0b10001; /* a has the integer value of 17 */
var b = 0b01101110; /*b has the binary value of n */
/* Printing values to demonstrate binary literals and their conversion to other types */
Console.WriteLine("Binary literal stored at a is: " + a);
Console.WriteLine("Binary literal stored at b is: " + b);
Console.WriteLine("Integer Value of a is: {0}", Convert.ToInt32(a));
Console.WriteLine("Character Value of b is: {0}", Convert.ToChar(b));
}
}
Output
Binary literal stored at a is: 17
Binary literal stored at b is: 110
Integer Value of a is: 17
Character Value of b is: n