简体   繁体   English

c# byte[] → string → byte[] issue

[英]c# byte[] → string → byte[] issue

Another strange question from me.我的另一个奇怪的问题。

I have this code:我有这个代码:

byte[] chks = Get64bitData();
string str = Encoding.UTF8.GetString(chks);
byte[] bts = Encoding.UTF8.GetBytes(str); 

Method Get64bitData returns 8 bytes array, then array got converted to string.方法Get64bitData返回8个字节的数组,然后将数组转换为字符串。 And then code converts string to byte array again, BUT new array is now has 16 bytes!然后代码再次将字符串转换为字节数组,但新数组现在有16个字节!

What type of hell is this and how avoid it?这是什么类型的地狱,如何避免?

Any random byte[] can not be converted to text safely as you have seen.正如您所见,任何随机字节 [] 都无法安全地转换为文本。 Use Convert.ToBase64String or BitConverter.ToString to convert byte arrays to string.使用Convert.ToBase64StringBitConverter.ToString将字节数组转换为字符串。

byte[] chks = Get64bitData();
string str = Convert.ToBase64String(chks);
byte[] bts = Convert.FromBase64String(str);

or using SoapHexBinary class in System.Runtime.Remoting.Metadata.W3cXsd2001或在System.Runtime.Remoting.Metadata.W3cXsd2001 中使用SoapHexBinary

byte[] chks = Get64bitData();
string str = new SoapHexBinary(chks).ToString();
byte[] bts = SoapHexBinary.Parse(str).Value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM