當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C# ASCII Char轉Byte用法及代碼示例


給定一個字符,任務是將其轉換為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

byte b = (byte) chr;

Step 3:Return or perform the operation on the byte 

下麵是上述方法的實現:

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);
    } 
}

輸出:

Byte of char 'G' : 71

方法二:使用Convert.ToByte(String, IFormatProvider)() 方法:此方法是 Convert 類方法。它用於將其他基本數據類型轉換為字節數據類型。

用法:

byte byt = Convert.ToByte(char); 

下麵是上述方法的實現:

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);
    } 
}

輸出:

Byte of char 'G' : 71

方法三:使用BitConverter()[0] 方法:Encoding.ASCII.GetBytes() 方法用於接受字符串作為參數並獲取字節數組。因此GetBytes()[0]用於將字符轉換為字符串後獲取字節。

用法:

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.

下麵是上述方法的實現:

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);
    } 
}

輸出:

Byte of char 'G' : 71



相關用法


注:本文由純淨天空篩選整理自SHUBHAMSINGH10大神的英文原創作品 How to Convert ASCII Char to Byte in C#?。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。