How to Convert ASCII Char to Byte in C#?
Given a char, the task is to convert this ASCII character into a Byte in C#.
Examples:
Input: chr = 'a'
Output: 97
Input: chr = 'H'
Output: 72
Method 1: Naive Approach
Step 1: Get the character.
Step 2: Convert the character using the Byte struct
byte b = (byte) chr;
Step 3: Return or perform the operation on the byte
Below is the implementation of the above approach:
C#
using System;
public class GFG{
static public void Main ()
{
char ch = 'G' ;
byte byt;
byt = ( byte )ch;
Console.WriteLine( "Byte of char \'" + ch + "\' : " + byt);
}
}
|
Output:
Byte of char 'G' : 71
Method 2: Using ToByte() Method: This method is a Convert class method. It is used to converts other base data types to a byte data type.
Syntax:
byte byt = Convert.ToByte(char);
Below is the implementation of the above approach:
C#
using System;
public class GFG{
static public void Main ()
{
char ch = 'G' ;
byte byt;
byt = Convert.ToByte(ch);
Console.WriteLine( "Byte of char \'" +
ch + "\' : " + byt);
}
}
|
Output:
Byte of char 'G' : 71
Method 3: Using GetBytes()[0] Method: The Encoding.ASCII.GetBytes() method is used to accepts a string as a parameter and get the byte array. Thus GetBytes()[0] is used to get the byte after converting the character into string.
Syntax:
byte byt = Encoding.ASCII.GetBytes(string str)[0];
Step 1: Get the character.
Step 2: Convert the character into string using ToString() method.
Step 3: Convert the string into byte using the GetBytes()[0] Method and store the converted string to the byte.
Step 4: Return or perform the operation on the byte.
Below is the implementation of the above approach:
C#
using System;
using System.Text;
public class GFG{
static public void Main ()
{
char ch = 'G' ;
string str = ch.ToString();
byte byt;
byt = Encoding.ASCII.GetBytes(str)[0];
Console.WriteLine( "Byte of char \'" +
ch + "\' : " + byt);
}
}
|
Output:
Byte of char 'G' : 71
Last Updated :
08 Feb, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...