Open In App

How to Convert ASCII Char to Byte in C#?

Last Updated : 06 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C#, converting an ASCII character to a byte is a common task, particularly useful in data encoding and manipulation. In this article, we will learn how to Convert ASCII Char to Byte in C#.

Example

Input: 'G'
Output: 71
Explanation: The ASCII character 'G' corresponds to the integer value 71, which is its representation in the ASCII table.

Syntax

byte b = (byte) chr;                                               #Naive Approach
byte byt = Convert.ToByte(chr); #Using ToByte() Method
byte byt = Encoding.ASCII.GetBytes(str)[0]; #Using GetBytes()[0] Method

Naive Approach

This method casts the character to a byte, providing its ASCII value.

Syntax

byte b = (byte) chr;

Example

C#
using System;

public class GFG {
    static public void Main() { 
        char a = 'G'; 
        byte b = (byte)a; 
        Console.WriteLine("'" + a + "\' : " + b);
    } 
}

Output
'G' : 71

Using ToByte() Method

This method is a Convert class method that converts other base data types to a byte data type.

Syntax

byte byt = Convert.ToByte(chr);

Example

C#
using System;

public class GFG {
    static public void Main() { 
        char a = 'G'; 
        byte b = Convert.ToByte(a); 
        Console.WriteLine("'" + a + "\' : " + b);
    } 
}

Output
'G' : 71

Using GetBytes()[0] Method

Syntax

byte byt = Encoding.ASCII.GetBytes(str)[0];

Example

C#
using System;
using System.Text;

public class GFG {
    static public void Main() { 
        char a = 'G'; 
        string s = a.ToString(); 
        byte b = Encoding.ASCII.GetBytes(s)[0]; 
        Console.WriteLine("'" + a + "\' : " + b);
    } 
}

Output
'G' : 71

Conclusion

Converting an ASCII character to a byte in C# can be easily achieved through various methods, including the naive approach, the Convert.ToByte() method, and the GetBytes() method. Each method serves specific scenarios, helping you effectively handle string and character manipulations in your applications.




Next Article
Article Tags :

Similar Reads