2

I get strange results when converting byte array to string and then converting the string back to byte array.

Try this:

     byte[] b = new byte[1];
    b[0] = 172;
    string s = Encoding.ASCII.GetString(b);

    byte[] b2 = Encoding.ASCII.GetBytes(s);
    MessageBox.Show(b2[0].ToString());

And the result for me is not 172 as I'd expect but... 63.

Why does it happen?

2
  • 172 is not a defined ASCII char. what you get is ? (63) Commented Oct 18, 2013 at 13:35
  • 1
    Obviously your example is a contrived case. What is the real problem you're trying to solve? Commented Oct 18, 2013 at 13:54

3 Answers 3

6

Why does it happen?

Because ASCII only contains values up to 127.

When faced with binary data which is invalid for the given encoding, Encoding.GetString can provide a replacement character, or throw an exception. Here, it's using a replacement character of ?.

It's not clear exactly what you're trying to achieve, but:

  • If you're converting arbitrary binary data to text, use Convert.ToBase64String instead; do not try to use an encoding, as you're not really representing text. You can use Convert.FromBase64String to then decode.
  • Encoding.ASCII is usually a bad choice, and certainly binary data including a byte of 172 is not ASCII text
  • You need to work out which encoding you're actually using. Personally I dislike using Encoding.Default unless you really know the data is in the default encoding for the platform you're working on. If you get the choice, using UTF-8 is a good one.
Sign up to request clarification or add additional context in comments.

Comments

3

ASCII encoding is a 7-bit encoding. If you take a look into generated string it contains "?" - unrecognized character. You might choose Encoding.Default instead.

3 Comments

If the OP is trying to encode arbitrary binary data and then decode it again, he shouldn't be using Encoding at all. Suggesting Encoding.Default is a bad idea, IMO.
I agree. Also, using string to contain binary data is a bad idea.
Well trying to encode it like that is a bad idea. Using base64 is inefficient, but if you only have a text-shaped pipe and you want to transport binary data, that will at least get it there safely...
1

ASCII is a seven bit character encoding, so 172 falls out of that range, so when converting to a string, it converts to "?" which is used for characters that cannot be represented.

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.