I found this little snippet to to transform a string into an array of bytes:
public byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
And this one to transform an array of bytes into a string:
public string GetString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
But I notice that the first one returns an array twice as big as the initial string (because sizeof(char) = 2) and every other slot in my array is a 0.
Example:
string = TEST
bytes[] = { 84, 0, 69, 0, 83, 0, 84, 0 };
I'm using this function to send packets in UDP, so I need my packets to be the smallest possible.
Why is the array twice bigger? How do I fix it?