在C#中将字符串转换为字节数组
先决条件:如何在C#中声明和使用byte[]?
C#中的字符串到字节数组的转换
在C#中,可以使用Encoding将字符串转换为字节数组。方法,它接受字符串作为参数并返回字节数组。ASCII.GetBytes()
注意:在C#中,字符串每个字符包含两个字节;每个字符包含两个字节。该方法将其转换为1字节。尽管如此,有时仍可能会丢失数据。
语法:
方法编码。包含各种重载方法,这里我们使用以下方法类型...ASCII.GetBytes()
byte[] Encoding.ASCII.GetBytes(String_Object);
示例
本示例包含一个常量字符串,并将其转换为byte[]
using System;
using System.Text;
namespace Test
{
class Program
{
static void Main(string[] args)
{
string str = "Hello World! I am [email protected]";
//读取所有字符作为字节并将其存储到byte[]
byte[] barr = Encoding.ASCII.GetBytes(str);
//使用字节值打印字符
for(int loop =0; loop<barr.Length-1; loop++)
{
Console.WriteLine("Byte of char \'" + str[loop] + "\' : " + barr[loop]);
}
//按ENTER退出
Console.ReadLine();
}
}
}输出结果
Byte of char 'H' : 72 Byte of char 'e' : 101 Byte of char 'l' : 108 Byte of char 'l' : 108 Byte of char 'o' : 111 Byte of char ' ' : 32 Byte of char 'W' : 87 Byte of char 'o' : 111 Byte of char 'r' : 114 Byte of char 'l' : 108 Byte of char 'd' : 100 Byte of char '!' : 33 Byte of char ' ' : 32 Byte of char 'I' : 73 Byte of char ' ' : 32 Byte of char 'a' : 97 Byte of char 'm' : 109 Byte of char ' ' : 32 Byte of char 'I' : 73 Byte of char 'n' : 110 Byte of char 'c' : 99 Byte of char 'l' : 108 Byte of char 'u' : 117 Byte of char 'd' : 100 Byte of char 'e' : 101 Byte of char 'H' : 72 Byte of char 'e' : 101 Byte of char 'l' : 108 Byte of char 'p' : 112 Byte of char '@' : 64 Byte of char '1' : 49 Byte of char '2' : 50 Byte of char '3' : 51
热门推荐
5 甄嬛传祝福语简短
10 送给姐姐简短的祝福语
11 给新年祝福语简短独特
12 迎新祝福语简短20字
13 贺寿祝福语长辈简短
14 广东新居入伙简短祝福语
15 姨父生日祝福语简短精辟
16 送礼祝福语男性生日简短
17 朋友弟弟生日祝福语简短
18 叔叔生日祝福语简短搞笑