转换字符串的byte []创建零字符 [英] Converting string to byte[] creates zero character
问题描述
在此转换功能
公共静态的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 = LIn 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 writesizeof(char)
, it returns2
.str.Length
is1
, so actually your code will bebyte[] bytes = new byte[2]
is the samebyte[2]
. So when you useBuffer.BlockCopy()
method, you actually copy2
bytes from a source array to a destination array. Which means yourGetBytes()
method returnsbytes[0] = 32
andbytes[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屋!