I’m trying to convert a byte[] to a string and back using Encoding.Unicode. Sometimes Encoding.Unicode is able to convert the byte[] to a string and sometimes the output is != the input. What am I doing wrong?
Thanks for your help.
public static void Main(string[] args)
{
Random rnd = new Random();
while(true)
{
Int32 random = rnd.Next(10, 20);
Byte[] inBytes = new Byte[random];
for(int i = 0; i < random; i++)
inBytes[i] = (Byte)rnd.Next(0, 9);
String inBytesString = Encoding.Unicode.GetString(inBytes, 0, inBytes.Length);
Byte[] outBytes = Encoding.Unicode.GetBytes(inBytesString);
if(inBytes.Length != outBytes.Length)
throw new Exception("?");
else
{
for(int i = 0; i < inBytes.Length; i++)
{
if(inBytes[i] != outBytes[i])
throw new Exception("?");
}
}
Console.WriteLine("OK");
}
}