繁体   English   中英

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

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

我的另一个奇怪的问题。

我有这个代码:

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

方法Get64bitData返回8个字节的数组,然后将数组转换为字符串。 然后代码再次将字符串转换为字节数组,但新数组现在有16个字节!

这是什么类型的地狱,如何避免?

正如您所见,任何随机字节 [] 都无法安全地转换为文本。 使用Convert.ToBase64StringBitConverter.ToString将字节数组转换为字符串。

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

或在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