将byte []转换为String并返回c#

mus*_*ium 1 c# string byte

我正在尝试使用Encoding.Unicode将byte []转换为字符串并返回.有时Encoding.Unicode能够将byte []转换为字符串,有时输出是!=输入.我究竟做错了什么?

谢谢你的帮助.

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 6

你不能使用Encoding:你必须使用像Convert.ToBase64String/Convert.FromBase64String这样的东西.

编码假设byte []根据特定规则进行格式化,而不是随机非字符串byte []的情况.

总结一下:

编码将任意字符串转换为格式化字节[]

Base-64将任意字节[]转换为格式化字符串