从字节数组转换为字符串时的结果奇怪 [英] Strange results when converting from byte array to string

查看:81
本文介绍了从字节数组转换为字符串时的结果奇怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将字节数组转换为字符串然后将字符串转换回字节数组时,我得到奇怪的结果.

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

尝试一下:

     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());

对我来说,结果不是172,而是63.

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

为什么会发生?

推荐答案

为什么会发生?

因为ASCII仅包含最多127个值.

Because ASCII only contains values up to 127.

当遇到对于给定编码无效的二进制数据时, Encoding.GetString 可以提供替换字符或引发异常.在这里,它使用?的替换字符.

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.

这篇关于从字节数组转换为字符串时的结果奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆