一个奇怪的事情在c#编码 [英] A weird thing in c# Encoding
问题描述
我将字节数组
转换为字符串
,并将此字符串
到字节数组
。
这两个字节数组是不同的。
I convert a byte array
to a string
, and I convert this string
to byte array
.
these two byte arrays are different.
如下:
byte[] tmp = Encoding.ASCII.GetBytes(Encoding.ASCII.GetString(b));
假设b是一个字节数组。
Suppose b is a byte array.
b [0] = 3,b [1] = 188,b [2] = 2 //十进制系统
b[0]=3, b[1]=188, b[2]=2 //decimal system
结果:
tmp [0] = 3, tmp [1] = 63,tmp [2] = 2
tmp[0]=3, tmp[1]=63, tmp[2]=2
这是我的问题,怎么了?
So that's my problem, what's wrong with it?
推荐答案
ASCII只有7位,所以其他无效。 默认情况下,它使用?
替换任何无效字节,这就是为什么你得到一个?
。
ASCII is 7-bit only, so others are invalid. By default it uses ?
to replace any invalid bytes and that's why you get a ?
.
对于8位字符集,您应该查找 扩展ASCII (后来定义为ISO 8859-1)或 代码页437 (这通常与扩展ASCII混淆,但实际上不是)。
For 8-bit character sets, you should be looking for either the Extended ASCII (which is later defined "ISO 8859-1") or the code page 437 (which is often confused with Extended ASCII, but in fact it's not).
您可以使用以下代码:
Encoding enc = Encoding.GetEncoding("iso-8859-1");
// For CP437, use Encoding.GetEncoding(437)
byte[] tmp = enc.GetBytes(enc.GetString(b));
这篇关于一个奇怪的事情在c#编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!