0

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?

2
  • 1
    Are you sure the data you're getting from Get64bitData is actually UTF8 text?
    – Dave Zych
    Commented Sep 9, 2015 at 15:55
  • 2
    You need to show us the contents of chks. Commented Sep 9, 2015 at 15:57

1 Answer 1

3

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;
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.