从字节数组转换为字符串时的结果奇怪 [英] 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.
尝试一下:
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:
- 如果要将任意二进制数据转换为文本,请使用
Convert.ToBase64String
代替;不要 not 尝试使用编码,因为您实际上并不能表示文本.您可以使用Convert.FromBase64String
然后解码. -
Encoding.ASCII
通常是一个错误的选择,并且肯定包括172个字节的二进制数据是 not ASCII文本 - 您需要确定您实际使用的是哪种编码.我个人不喜欢使用
Encoding.Default
,除非您真的知道数据使用的是您正在使用的平台的默认编码.如果可以的话,使用UTF-8是一个不错的选择.
- 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 useConvert.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屋!
查看全文