给定一个字符,任务是将该ASCII字符转换为C#中的字节。
例子:
Input: chr = 'a'
Output: 97
Input: chr = 'H'
Output: 72
方法1:天真的方法
Step 1: Get the character.
Step 2: Convert the character using the Byte struct
Step 3: Return or perform the operation on the byte
下面是上述方法的实现:
C#
byte b = (byte) chr;
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);
}
}
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);
}
}
输出:
// 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);
}
}
方法2:使用ToByte ()方法:此方法是Convert类方法。它用于将其他基本数据类型转换为字节数据类型。
句法:
Byte of char 'G' : 71
下面是上述方法的实现:
C#
byte byt = Convert.ToByte(char);
输出:
// 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);
}
}
方法3:使用GetBytes ()[0]方法:编码。 ASCII。 GetBytes()方法用于接受字符串作为参数并获取字节数组。因此,在将字符转换为字符串之后,使用GetBytes()[0]获取字节。
句法:
Byte of char 'G' : 71
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.
下面是上述方法的实现:
C#
byte byt = Encoding.ASCII.GetBytes(string str)[0];
输出:
// 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);
}
}