C# Binary Literals

Muhammad Zeeshan Oct 12, 2023
C# Binary Literals

Binary Literal is the name given to the new literal introduced in version 7.0 of the C# programming language. The binary value is stored in a variable using the literal representation of binary numbers, and the representation for the binary literal is the letter by 0b.

This article will discuss how to write binary literal using the C#.

Binary Literals in C#

Bitmasks are where you’ll find binary literals being employed. Literal refers to the values that are constant throughout the expression.

A literal is a value utilized by the variables in the expression. Different kinds of literal can be used before C# 7.0 release. These literals include an integer, float, character, and string.

Let’s have an example. To begin, import the following libraries.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

After that, we’ll produce binary literals by prefixing them with 0b.

var val1 = 0b01000111;

Following that, we will output the character value on the console by utilizing the Convert.ToChar() method.

Console.WriteLine("Int value of val1 is: " + val1);
Console.WriteLine("Char value of val1 is: {0}", Convert.ToChar(val1));

Complete Source Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace BinaryLiteralsByZeeshan {
  public class Program {
    public static void Main(string[] args) {
      var val1 = 0b01000111;
      Console.WriteLine("Int value of val1 is: " + val1);
      Console.WriteLine("Char value of val1 is: {0}", Convert.ToChar(val1));
    }
  }
}

Output:

Int value of val1 is: 71
Char value of val1 is: G
Muhammad Zeeshan avatar Muhammad Zeeshan avatar

I have been working as a Flutter app developer for a year now. Firebase and SQLite have been crucial in the development of my android apps. I have experience with C#, Windows Form Based C#, C, Java, PHP on WampServer, and HTML/CSS on MYSQL, and I have authored articles on their theory and issue solving. I'm a senior in an undergraduate program for a bachelor's degree in Information Technology.

LinkedIn

Related Article - Csharp Binary