c#将字符串转换为数组,在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

{

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

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值