0

From the docs, Encode should provide a way to convert bytes to a string and back again. However, this test case gives very different results after the decode. The input data 'bytes' is 6 elements, but the output data 'outputData' is 17 elements. Why is this?

    byte[] bytes = new byte[] { 24, 48, 49, 127, 250, 255, 1 };

    char[] charData = Encoding.UTF7.GetChars(bytes);
    byte[] outputData = Encoding.UTF7.GetBytes(charData);
3
  • You use text encodings when you have arbitrary sets of characters and need to control their byte representations. Not for taking an arbitrary set of bytes and turning them into characters. You have a set of bytes that a UTF-7 encoding of characters would never produce. It's not surprising that you can't round trip them when trying to use it the wrong way around. Commented Feb 20, 2020 at 14:48
  • 3
    If you have an arbitrary set of bytes and need to round-trip them via strings, you should be looking for something that is designed to work that way around - e.g. Base-64 encoding. Commented Feb 20, 2020 at 14:51
  • UTF7Encoding does not provide error detection. When invalid bytes are encountered, UTF7Encoding generally emits the invalid bytes........, decoding with Encoding.UTF8.GetBytes(charData); shows this. Commented Feb 20, 2020 at 14:54

1 Answer 1

2

From Damien_The_Unbeliever's suggestion, found Convert instead

    byte[] bytes = new byte[] { 24, 48, 49, 127, 250, 255, 1 };

    // encode
    string byteString = Convert.ToBase64String(bytes);
    byte[] byteList = Convert.FromBase64String(byteString);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.