问题描述
我正在尝试使用Encoding.Unicode将byte []转换为字符串并返回.有时Encoding.Unicode能够将byte []转换为字符串,有时输出是!=输入.我在做什么错了?
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?
感谢您的帮助.
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");
}
}
推荐答案
您不能为此使用编码:您必须使用类似Convert.ToBase64String/Convert.FromBase64String之类的东西.
You cannot use Encoding for that: you must use something like Convert.ToBase64String / Convert.FromBase64String.
编码假定byte []是根据特定规则进行格式化的,而随机非字符串byte []则不是这种情况.
Encoding assumes the byte[] is formatted according to specific rules, which are not the case for a random non-string byte[].
总结一下:
编码将任意字符串转换为格式化字节[/]或从格式化字节[]
An Encoding turns an arbitrary string to/from a formatted byte[]
Base-64将任意字节[]转换为格式化字符串,或从格式化字符串转换为
Base-64 turns an arbitrary byte[] to/from a formatted string
这篇关于将byte []转换为String并返回c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!