简体   繁体   中英

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. And then code converts string to byte array again, BUT new array is now has 16 bytes!

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.

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

or using SoapHexBinary class in System.Runtime.Remoting.Metadata.W3cXsd2001

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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