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#
// C# program to convert // ascii char to byte. using System; public class GFG{ static public void Main () { char ch = 'G' ; // Creating byte byte byt; // converting character into byte byt = ( byte )ch; // printing character with byte value 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#
// C# program to convert // ascii char to byte. using System; public class GFG{ static public void Main () { char ch = 'G' ; // Creating byte byte byt; // converting character into byte // using Convert.ToByte() method byt = Convert.ToByte(ch); // printing character with byte value 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#
// C# program to convert // ascii char to byte. using System; using System.Text; public class GFG{ static public void Main () { char ch = 'G' ; // convert to string // using the ToString() method string str = ch.ToString(); // Creating byte byte byt; // converting character into byte // using GetBytes() method byt = Encoding.ASCII.GetBytes(str)[0]; // printing character with byte value Console.WriteLine( "Byte of char \'" + ch + "\' : " + byt); } } |
Output:
Byte of char 'G' : 71