2014-03-01 182 views
0

我不知道为什么,但是当你做的下一件事,你永远不会得到相同的原始字节数组:获取从字节数组字符数组,然后返回字节数组

var b = new byte[] {252, 2, 56, 8, 9}; 
var g = System.Text.Encoding.ASCII.GetChars(b); 
var f = System.Text.Encoding.ASCII.GetBytes(g); 

如果你愿意运行这段代码你会看到b!= f,为什么? 有什么办法将字节转换为字符,然后回到字节,并得到原始字节数组相同?

+5

因为'252'不能用作ASCII字符(它是7位)。所以在任何任意字节数组和字符串之间进行转换可能是有损的。 –

+0

你想用字符做什么? –

+0

@ L.B我如何解决它? –

回答

2

byte value can be 0 to 255

当字节值> 127,然后导致的

System.Text.Encoding.ASCII.GetChars() 

总是'?'具有价值

因此,

System.Text.Encoding.ASCII.GetBytes() 

结果总是为那些(错误值)有起始字节值> 127


如果您需要TABLE ASCII -II然后你可以做如下

 var b = new byte[] { 252, 2, 56, 8, 9 }; 
     //another encoding 
     var e = Encoding.GetEncoding("437"); 
     //252 inside the mentioned table is ⁿ and now you have it 
     var g = e.GetString(b); 
     //now you can get the byte value 252 
     var f = e.GetBytes(g); 

类似的帖子,你可以阅读

How to convert the byte 255 to a signed char in C#

How can I convert extended ascii to a System.String?

-2

唯一的区别是第一个字节:252.因为ascii字符是1字节的有符号字符,它的取值范围是-128到127.实际上你的输入是不正确的。 signed char不能为252.

+0

http://en.wikipedia。org/wiki/ASCII –

+0

我并不是在谈论真正的ascii。我在谈论代码中的ascii。我故意写这种方式很容易理解。我知道没有什么叫ascii无符号字符。 –

+0

ascii没有负值。 –

0

为什么不使用字符?

var b = new byte[] {252, 2, 56, 8, 9}; 
var g = new char[b.Length]; 
var f = new byte[g.Length]; // can also be b.Length, doens't really matter 
for (int i = 0; i < b.Length; i++) 
{ 
    g[i] = Convert.ToChar(b[i]); 
} 
for (int i = 0; i < f.Length; i++) 
{ 
    f[i] = Convert.ToByte(g[i]); 
}