加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 将字符串转换为byte []创建零字符

发布时间:2020-12-15 06:36:45 所属栏目:百科 来源:网络整理
导读:在这个转换函数中 public static byte[] GetBytes(string str){ byte[] bytes = new byte[str.Length * sizeof(char)]; System.Buffer.BlockCopy(str.ToCharArray(),bytes,bytes.Length); return bytes;}byte[] test = GetBytes("abc"); 结果数组包含零个字
在这个转换函数中
public static byte[] GetBytes(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(),bytes,bytes.Length);
    return bytes;
}

byte[] test = GetBytes("abc");

结果数组包含零个字符

test = [97,98,99,0]

当我们将byte []转换成字符串,结果是

string test = "a b c "

我们如何使它不会创建这些零

解决方法

首先让我们来看看你的代码错了什么 char是.NET框架中的16位(2字节).这意味着当你写sizeof(char)时,它返回2. str.Length是1,所以实际上你的代码将是byte [] bytes = new byte [2]是相同的字节[2].因此,当您使用 Buffer.BlockCopy()方法时,实际上将2个字节从源数组复制到目标数组.这意味着如果您的字符串为“”,您的GetBytes()方法返回字节[0] = 32,字节[1] = 0.

尝试使用Encoding.ASCII.GetBytes().

When overridden in a derived class,encodes all the characters in the
specified string into a sequence of bytes.

const string input = "Soner Gonul";

byte[] array = Encoding.ASCII.GetBytes(input);

foreach ( byte element in array )
{
     Console.WriteLine("{0} = {1}",element,(char)element);
}

输出:

83 = S
111 = o
110 = n
101 = e
114 = r
32 =
71 = G
111 = o
110 = n
117 = u
108 = l

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读