📌  相关文章
📜  在C#中将字符串转换为其等效字节数组

📅  最后修改于: 2021-05-29 17:46:14             🧑  作者: Mango

给定一个字符串,任务是将该字符串转换为C#中的Byte数组。

例子:

Input: aA
Output: [97, 65 ]
  
Input: Hello
Output: [ 72, 101, 108, 108, 111 ]

方法1:

使用ToByte ()方法:此方法是Convert类的方法。它用于将其他基本数据类型转换为字节数据类型。

句法:

byte byt = Convert.ToByte(char); 

下面是上述方法的实现:

C#
// C# program to convert a given
// string to its equivalent byte[]
    
using System;
  
public class GFG{
    
    static public void Main ()
    { 
        string str = "GeeksForGeeks"; 
    
        // Creating byte array of string length 
        byte[] byt = new byte[str.Length]; 
    
        // converting each character into byte 
        // and store it
        for (int i = 0; i < str.Length; i++) { 
            byt[i] = Convert.ToByte(str[i]); 
        } 
    
        // printing characters with byte values
        for(int i =0; i


C#
// C# program to convert a given
// string to its equivalent byte[]
    
using System;
using System.Text;
  
public class GFG{
    
    static public void Main ()
    { 
        string str = "GeeksForGeeks"; 
    
        // Creating byte array of string length 
        byte[] byt; 
    
        // converting each character into byte 
        // and store it
        byt = Encoding.ASCII.GetBytes(str);
    
        // printing characters with byte values
        for(int i =0; i


输出:

Byte of char 'G' : 71
Byte of char 'e' : 101
Byte of char 'e' : 101
Byte of char 'k' : 107
Byte of char 's' : 115
Byte of char 'F' : 70
Byte of char 'o' : 111
Byte of char 'r' : 114
Byte of char 'G' : 71
Byte of char 'e' : 101
Byte of char 'e' : 101
Byte of char 'k' : 107
Byte of char 's' : 115

方法2:

使用GetBytes ()方法: The Encoding ASCII。 GetBytes()方法用于接受字符串作为参数并获取字节数组。

句法:

byte[] byte_array = Encoding.ASCII.GetBytes(string str); 

C#

// C# program to convert a given
// string to its equivalent byte[]
    
using System;
using System.Text;
  
public class GFG{
    
    static public void Main ()
    { 
        string str = "GeeksForGeeks"; 
    
        // Creating byte array of string length 
        byte[] byt; 
    
        // converting each character into byte 
        // and store it
        byt = Encoding.ASCII.GetBytes(str);
    
        // printing characters with byte values
        for(int i =0; i

输出:

Byte of char 'G' : 71
Byte of char 'e' : 101
Byte of char 'e' : 101
Byte of char 'k' : 107
Byte of char 's' : 115
Byte of char 'F' : 70
Byte of char 'o' : 111
Byte of char 'r' : 114
Byte of char 'G' : 71
Byte of char 'e' : 101
Byte of char 'e' : 101
Byte of char 'k' : 107
Byte of char 's' : 115