Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange results when converting from byte array to string

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?

like image 286
RRM Avatar asked Jun 12 '26 01:06

RRM


2 Answers

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.
like image 136
Jon Skeet Avatar answered Jun 14 '26 16:06

Jon Skeet


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.

like image 30
Krzysiek Bronek Avatar answered Jun 14 '26 16:06

Krzysiek Bronek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!