给定一个字符串,任务是将该字符串转换为C#中的Byte数组。
例子:
Input: aA
Output: [97, 65 ]
Input: Hello
Output: [ 72, 101, 108, 108, 111 ]
方法1:
使用ToByte ()方法:此方法是Convert类的方法。它用于将其他基本数据类型转换为字节数据类型。
句法:
byte byt = Convert.ToByte(char);
Step 1: Get the string.
Step 2: Create a byte array of the same length as of string.
Step 3: Traverse over the string to convert each character into byte using the ToByte() Method and store all the bytes to the byte array.
Step 4: Return or perform the operation on the byte array.
下面是上述方法的实现:
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);
Step 1: Get the string.
Step 2: Create an empty byte array.
Step 3: Convert the string into byte[] using the GetBytes() Method and store all the convert string to the byte array.
Step 4: Return or perform the operation on the byte array.
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