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.
charis 16-bit (2 byte) in .NET framework. Which means when you writesizeof(char), it returns2.str.Lengthis1, so actually your code will bebyte[] bytes = new byte[2]is the samebyte[2]. So when you useBuffer.BlockCopy()method, you actually copy2bytes from a source array to a destination array. Which means yourGetBytes()method returnsbytes[0] = 32andbytes[1] = 0if your string is" ".Try to use
Encoding.ASCII.GetBytes()instead.Output: