The Binary Literals feature in C# enables us to work with binary values within C# applications. This functionality permits the storage of binary values in variables.
C# offers 0b for binary and 0x for hexadecimal literals to represent values in different number systems. These specific prefixes are understood by the C# compiler, which interprets the values accordingly.
Let's see an example.
C# Binary literals Example
using System;
namespace CSharpFeatures
{
class BinaryLiteralsExample
{
public static void Main()
{
// Creating binary literals
int a = 0b1010;
// Creating hexadecimal literals
int b = 0x00A;
Console.WriteLine(a);
Console.WriteLine(b);
}
}
}
Output:
We have the option to utilize digit separators in binary literals to enhance the readability of the value.
C# Binary Literal Example
using System;
namespace CSharpFeatures
{
class BinaryLiteralsExample
{
public static void Main()
{
// Separating binary literals
int a = 0b1_01_0;
// Separating hexadecimal literals
int b = 0x00_A;
Console.WriteLine(a);
Console.WriteLine(b);
}
}
}
Output: