转换字符串的byte []创建零字符 [英] Converting string to byte[] creates zero character

查看:147
本文介绍了转换字符串的byte []创建零字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此转换功能

 公共静态的byte [] GetBytes会(字符串str)
{
    字节[]字节=新的字节[str.Length *的sizeof(字符)];
    System.Buffer.BlockCopy(str.ToCharArray(),0,字节,0,bytes.Length);
    返回字节;
}字节[] =测试GetBytes会(ABC);

结果数组包含零字符

 测试= 97,0,98,0,99,0]

而当我们转换的byte []返回的字符串,其结果是

 字符串测试=A B C

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


解决方案

首先让我们看一下你的code确实错了。 字符 是16位(2字节)的.NET框架。当你写这意味着的sizeof(char)的,它返回 2 str.Length 1 ,所以实际上你的code将字节[]字节=新的字节[2] 是一样的字节[2] 。因此,当您使用 Buffer.BlockCopy() 方法,你居然复制 2 从源数组到目标数组字节。这意味着你的 GetBytes会()方法的返回值字节[0] = 32 字节[1 ] = 0 如果你的字符串是

尝试使用 Encoding.ASCII.GetBytes() 来代替。


  

当在覆盖在派生类中,连接codeS中的所有字符
  指定的字符串为一个字节序列。


 常量字符串输入=Soner格尼尔byte []数组= Encoding.ASCII.GetBytes(输入);的foreach(数组元素的字节)
{
     Console.WriteLine({0} = {1},元素,(char)的元素);
}

输出:

  83 = S
111 = O
110 = N
101 = E
114 = R
32 =
71 = G
111 = O
110 = N
117 = U
108 = L

In this convert function

public static byte[] GetBytes(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}

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

The resulting array contains zero character

test = [97, 0, 98, 0, 99, 0]

And when we convert byte[] back to string, the result is

string test = "a b c "

How do we make it so it doesn't create those zeroes

解决方案

First let's look at what your code does wrong. char is 16-bit (2 byte) in .NET framework. Which means when you write sizeof(char), it returns 2. str.Length is 1, so actually your code will be byte[] bytes = new byte[2] is the same byte[2]. So when you use Buffer.BlockCopy() method, you actually copy 2 bytes from a source array to a destination array. Which means your GetBytes() method returns bytes[0] = 32 and bytes[1] = 0 if your string is " ".

Try to use Encoding.ASCII.GetBytes() instead.

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);
}

Output:

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

这篇关于转换字符串的byte []创建零字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆